返回一个与给定数组形状相同的新数组,但更改NumPy中的默认类型


要返回一个与给定数组形状和类型相同的新数组,请在Python NumPy中使用**numpy.empty_like()**方法。它返回一个未初始化(任意)数据的数组,其形状和类型与原型相同。这里第一个参数是原型的形状和数据类型(类似数组),这些属性定义了返回数组的相同属性。第二个参数是**dtype**,即我们想要的结果数组的数据类型。

顺序会覆盖结果的内存布局。“C”表示C顺序,“F”表示F顺序,“A”表示如果原型是Fortran连续的则为“F”,否则为“C”。“K”表示尽可能匹配原型的布局。形状会覆盖结果的形状。如果order='K'并且维数不变,则将尝试保持顺序,否则,隐含order='C'。overrides参数会覆盖结果的数据类型。

如果subok参数为True,则新创建的数组将使用原型的子类类型,否则它将是基类数组。默认为True。

步骤

首先,导入所需的库:

import numpy as np

使用Python NumPy中的numpy.array()方法创建一个新数组:

arr = np.array([[35.7, 56.2, 66.4], [88.2, 73.7, 98.3]])

显示数组:

print("Array...
",arr)

获取数组的类型:

print("
Array type...
", arr.dtype)

获取数组的维度:

print("
Array Dimensions...
", arr.ndim)

要返回一个与给定数组形状和类型相同的新数组,请在Python NumPy中使用numpy.empty_like()方法:

newArr = np.empty_like(arr, dtype = int)
print("
New Array..
", newArr)

获取新数组的类型:

print("
New Array type...
", newArr.dtype)

获取新数组的维度:

print("
New Array Dimensions...
", newArr.ndim)

示例

import numpy as np

# Create a new array using the numpy.array() method in Python Numpy
arr = np.array([[35.7, 56.2, 66.4], [88.2, 73.7, 98.3]])

# Display the array
print("Array...
",arr) # Get the type of the array print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
", arr.ndim) # To return a new array with the same shape and type as a given array, use the numpy.empty_like() method in Python Numpy # It returns the array of uninitialized (arbitrary) data with the same shape and type as prototype. # The 1st parameter here is the shape and data-type of prototype(array-like) that define these same attributes of the returned array. # The 2nd parameter is the dtype i.e. the data-type we want for the resultant array newArr = np.empty_like(arr, dtype = int) print("
New Array..
", newArr) # Get the type of the new array print("
New Array type...
", newArr.dtype) # Get the dimensions of the new array print("
New Array Dimensions...
", newArr.ndim)

输出

Array...
[[35.7 56.2 66.4]
[88.2 73.7 98.3]]

Array type...
float64

Array Dimensions...
2

New Array..
[[4630221145643784602 4633106264155068826 4634372901550266778]
[4635906940173339853 4634886593382763725 4636617664489534259]]

New Array type...
int64

New Array Dimensions...
2

更新于:2022年2月10日

90 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.