Numpy 简明教程

NumPy - Array Creation Routines

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

A new ndarray object can be constructed by any of the following array creation routines or using a low-level ndarray constructor.

numpy.empty

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

It creates an uninitialized array of specified shape and dtype. It uses the following constructor −

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

构造函数需要以下参数。

The constructor takes the following parameters.

Sr.No.

Parameter & Description

1

Shape Shape of an empty array in int or tuple of int

2

Dtype Desired output data type. Optional

3

Order 'C' for C-style row-major array, 'F' for FORTRAN style column-major array

Example

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

The following code shows an example of an empty array.

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

输出如下 −

The output is as follows −

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

Note − 由于数组中的元素未初始化,所以它们显示随机值。

Note − The elements in an array show random values as they are not initialized.

numpy.zeros

返回一个指定的尺寸的新数组,并用零填充。

Returns a new array of specified size, filled with zeros.

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

构造函数需要以下参数。

The constructor takes the following parameters.

Sr.No.

Parameter & Description

1

Shape Shape of an empty array in int or sequence of int

2

Dtype Desired output data type. Optional

3

Order 'C' for C-style row-major array, 'F' for FORTRAN style column-major array

Example 1

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

输出如下 −

The output is as follows −

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

Example 2

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

现在,输出如下 −

Now, the output would be as follows −

[0  0  0  0  0]

Example 3

# custom type
import numpy as np
x = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print x

它应该产生以下输出 −

It should produce the following output −

[[(0,0)(0,0)]
 [(0,0)(0,0)]]

numpy.ones

返回指定尺寸和类型的新数组,并用 1 填充。

Returns a new array of specified size and type, filled with ones.

numpy.ones(shape, dtype = None, order = 'C')

构造函数需要以下参数。

The constructor takes the following parameters.

Sr.No.

Parameter & Description

1

Shape Shape of an empty array in int or tuple of int

2

Dtype Desired output data type. Optional

3

Order 'C' for C-style row-major array, 'F' for FORTRAN style column-major array

Example 1

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

输出如下 −

The output is as follows −

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

Example 2

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

现在,输出如下 −

Now, the output would be as follows −

[[1  1]
 [1  1]]