可以通过以下任何数组创建或使用低级ndarray构造函数来构造新的 ndarray对象 。
numpy.empty
它创建指定维度和dtype的未初始化数组。它使用以下构造函数-
numpy.empty(shape, dtype=float, order=C)
构造函数采用以下参数。
| Sr.No. | Parameter & 描述 |
|---|---|
| 1 | shape int或int元组中的空数组的维度 |
| 2 | Dtype 所需的输出数据类型。可选的 |
| 3 | order " C"表示C样式的行主数组," F"表示FORTRAN样式的行主数组 |
以下代码显示了一个空数组的示例。
import numpy as np x = np.empty([3,2], dtype = int) print x
输出如下-
[[22649312 1701344351] [1818321759 1885959276] [16779776 156368896]]
注意-数组中的元素显示随机值,因为它们没有初始化。
numpy.zeros
返回指定大小的新数组,并用零填充。
numpy.zeros(shape, dtype=float, order=C)
构造函数采用以下参数。
| Sr.No. | Parameter & 描述 |
|---|---|
| 1 | shape int或int序列中的空数组的维度 |
| 2 | Dtype 所需的输出数据类型。可选的 |
| 3 | order " C"表示C样式的行主数组," F"表示FORTRAN样式的行主数组 |
示例1
# 五个零的数组。默认 dtype 是 float import numpy as np x = np.zeros(5) print x
输出如下-
[ 0. 0. 0. 0. 0.]
示例2
import numpy as np x = np.zeros((5,), dtype = np.int) print x
现在,输出将如下所示:
[0 0 0 0 0]
示例3
# 自定义类型 import numpy as np x = np.zeros((2,2), dtype = [(x, i4), (y, i4)]) print x
它应该产生以下输出-
[[(0,0)(0,0)] [(0,0)(0,0)]]
numpy.ones
返回指定大小和类型的新数组,并填充为1。
numpy.ones(shape, dtype=None, order=C)
构造函数采用以下参数。
| Sr.No. | Parameter & 描述 |
|---|---|
| 1 | shape int或int元组中的空数组的维度 |
| 2 | Dtype 所需的输出数据类型。可选的 |
| 3 | order " C"表示C样式的行主数组," F"表示FORTRAN样式的行主数组 |
示例1
# 五个一的数组。默认 dtype 是 float import numpy as np x = np.ones(5) print x
输出如下-
[ 1. 1. 1. 1. 1.]
示例2
import numpy as np x = np.ones([2,2], dtype = int) print x
现在,输出将如下所示:
[[1 1] [1 1]]
本文介绍了如何使用NumPy库中的empty,zeros,ones函数创建不同维度和类型的数组,包括参数解释和示例。这些函数分别是生成未初始化、全零和全一数组的方法。
https://www.learnfk.com/numpy/numpy-array-creation-routines.html
388

被折叠的 条评论
为什么被折叠?



