返回一个具有给定形状的新数组,但不初始化条目,并更改 NumPy 中的默认类型


要返回一个具有给定形状的新数组,但不初始化条目,请在 Python NumPy 中使用 **numpy.empty()** 方法。第一个参数是空数组的形状。empty() 的默认类型是浮点数。我们使用第二个参数“**dtype**”将其更改为“int”。

dtype 是数组所需的输出数据类型,例如 numpy.int8。默认值为 numpy.float64。order 指示是否以行主序(C 样式)或列主序(Fortran 样式)方式在内存中存储多维数据。

empty() 函数返回一个具有给定形状、dtype 和 order 的未初始化(任意)数据的数组。对象数组将初始化为 None。

NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持广泛的硬件和计算平台,并且与分布式、GPU 和稀疏数组库配合良好。

步骤

首先,导入所需的库:

import numpy as np

要返回一个具有给定形状的新数组,但不初始化条目,请在 Python NumPy 中使用 numpy.empty() 方法:

arr = np.empty([3, 3], dtype = int)

显示数组:

print("Array...
",arr)

获取数组的类型:

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

获取数组的维度:

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

获取数组中的元素数量:

print("
Number of elements...
", arr.size)

示例

import numpy as np

# To return a new array of given shape, without initializing entries, use the numpy.empty() method in Python Numpy
# The 1st parameter is the Shape of the empty array
# The default type for empty() is float. We are changing it to "int" using the 2nd parameter i.e. "dtype"
arr = np.empty([3, 3], dtype = int)

# Display the array
print("Array...
",arr) # Get the type of the array print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimensions...
", arr.ndim) # Get the number of elements in the Array print("
Number of elements...
", arr.size)

输出

Array...
[0                         0             7307491100562890867]
[8390032522262880356 7232535146496532584 2334111870318900321]
[8314046642435483764 7953674041135475819 160]]

Array type...
int64

Our Array Dimensions...
2

Number of elements...
9

更新于: 2022年2月10日

486 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.