目录

NumPy - 阵列创建例程( Array Creation Routines)

可以通过以下任何数组创建例程或使用低级ndarray构造函数构造新的ndarray对象。

numpy.empty

它创建一个指定形状和dtype的未初始化数组。 它使用以下构造函数 -

numpy.empty(shape, dtype = float, order = 'C')

构造函数采用以下参数。

Sr.No. 参数和描述
1

Shape

int的int或元组中的空数组的形状

2

Dtype

期望的输出数据类型。 可选的

3

Order

对于C风格的行主阵列,'C',对于FORTRAN样式的列主阵列,'F'

例子 (Example)

以下代码显示了一个空数组的示例。

import numpy as np 
x = np.empty([3,2], dtype = int) 
print x

输出如下 -

[[22649312    1701344351] 
 [1818321759  1885959276] 
 [16779776    156368896]]

Note - 数组中的元素显示随机值,因为它们未初始化。

numpy.zeros

返回指定大小的新数组,用零填充。

numpy.zeros(shape, dtype = float, order = 'C')

构造函数采用以下参数。

Sr.No. 参数和描述
1

Shape

int或int序列中空数组的形状

2

Dtype

期望的输出数据类型。 可选的

3

Order

对于C风格的行主阵列,'C',对于FORTRAN样式的列主阵列,'F'

例子1 (Example 1)

# array of five zeros. Default dtype is float 
import numpy as np 
x = np.zeros(5) 
print x

输出如下 -

[ 0.  0.  0.  0.  0.]

例子2 (Example 2)

import numpy as np 
x = np.zeros((5,), dtype = np.int) 
print x

现在,输出如下 -

[0  0  0  0  0]

例子3 (Example 3)

# custom type 
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. 参数和描述
1

Shape

int的int或元组中的空数组的形状

2

Dtype

期望的输出数据类型。 可选的

3

Order

对于C风格的行主阵列,'C',对于FORTRAN样式的列主阵列,'F'

例子1 (Example 1)

# array of five ones. Default dtype is float 
import numpy as np 
x = np.ones(5) 
print x

输出如下 -

[ 1.  1.  1.  1.  1.]

例子2 (Example 2)

import numpy as np 
x = np.ones([2,2], dtype = int) 
print x

现在,输出如下 -

[[1  1] 
 [1  1]]
↑回到顶部↑
WIKI教程 @2018