在 Numpy 中返回一个具有给定形状和类型的新数组,但不初始化其中的元素
要返回一个具有给定形状和类型的新数组,而不初始化其元素,请在 Python Numpy 中使用 **ma.empty()** 方法。第一个参数设置空数组的形状。**dtype** 参数设置数组所需的输出数据类型。该方法返回一个具有给定形状、dtype 和顺序的未初始化(任意)数据的数组。对象数组将初始化为 None。
步骤
首先,导入所需的库 -
import numpy as np import numpy.ma as ma
使用 Python Numpy 中的 ma.empty() 方法返回一个具有给定形状和类型的新数组,但不初始化其中的元素 -
arr = ma.empty((5, 5),dtype = np.int32)
显示我们的数组 -
print("Array...",arr)
获取数组的维度 -
print("Array Dimensions...",arr.ndim)
获取数组的形状 -
print("Our Array Shape...",arr.shape)
获取数组的元素数量 -
print("Elements in the Array...",arr.size)
示例
# Python ma.MaskedArray - Return a new array of given shape and type without initializing entries import numpy as np import numpy.ma as ma # To return a new array of given shape and type, without initializing entries, use the ma.empty() method in Python Numpy # The 1st parameter sets the shape of the empty array # The dtype parameter sets the desired output data-type for the array arr = ma.empty((5, 5),dtype = np.int32) # Displaying our array print("Array...",arr) # Get the dimensions of the Array print("Array Dimensions...",arr.ndim) # Get the shape of the Array print("Our Array Shape...",arr.shape) # Get the number of elements of the Array print("Elements in the Array...",arr.size)
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Array... [[ 0 0 0 0 117] [ 99 104 32 102 105] [108 101 32 111 114] [ 32 100 105 114 101] [ 99 116 111 114 121]] Array Dimensions... 2 Our Array Shape... (5, 5) Elements in the Array... 25
广告