新的ndarray對象可以通過任何下列數(shù)組創(chuàng)建例程或使用低級ndarray構(gòu)造函數(shù)構(gòu)造。
numpy.empty它創(chuàng)建指定形狀和dtype的未初始化數(shù)組。 它使用以下構(gòu)造函數(shù):
numpy.empty(shape, dtype = float, order = 'C')
構(gòu)造器接受下列參數(shù):
| 序號 | 參數(shù)及描述 |
|---|---|
| 1. | Shape 空數(shù)組的形狀,整數(shù)或整數(shù)元組 |
| 2. | Dtype 所需的輸出數(shù)組類型,可選 |
| 3. | Order 'C'為按行的 C 風(fēng)格數(shù)組,'F'為按列的 Fortran 風(fēng)格數(shù)組 |
下面的代碼展示空數(shù)組的例子:
import numpy as np
x = np.empty([3,2], dtype = int)
print x
輸出如下:
[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
注意:數(shù)組元素為隨機值,因為它們未初始化。
numpy.zeros返回特定大小,以 0 填充的新數(shù)組。
numpy.zeros(shape, dtype = float, order = 'C')
構(gòu)造器接受下列參數(shù):
| 序號 | 參數(shù)及描述 |
|---|---|
| 1. | Shape 空數(shù)組的形狀,整數(shù)或整數(shù)元組 |
| 2. | Dtype 所需的輸出數(shù)組類型,可選 |
| 3. | Order 'C'為按行的 C 風(fēng)格數(shù)組,'F'為按列的 Fortran 風(fēng)格數(shù)組 |
# 含有 5 個 0 的數(shù)組,默認(rèn)類型為 float
import numpy as np
x = np.zeros(5)
print x
輸出如下:
[ 0. 0. 0. 0. 0.]
import numpy as np
x = np.zeros((5,), dtype = np.int)
print x
輸出如下:
[0 0 0 0 0]
# 自定義類型
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 填充的新數(shù)組。
numpy.ones(shape, dtype = None, order = 'C')
構(gòu)造器接受下列參數(shù):
| 序號 | 參數(shù)及描述 |
|---|---|
| 1. | Shape 空數(shù)組的形狀,整數(shù)或整數(shù)元組 |
| 2. | Dtype 所需的輸出數(shù)組類型,可選 |
| 3. | Order 'C'為按行的 C 風(fēng)格數(shù)組,'F'為按列的 Fortran 風(fēng)格數(shù)組 |
# 含有 5 個 1 的數(shù)組,默認(rèn)類型為 float
import numpy as np
x = np.ones(5) print x
輸出如下:
[ 1. 1. 1. 1. 1.]
import numpy as np
x = np.ones([2,2], dtype = int)
print x
輸出如下:
[[1 1]
[1 1]]