這一章中,我們會(huì)討論 NumPy 的多種數(shù)組屬性。
ndarray.shape
這一數(shù)組屬性返回一個(gè)包含數(shù)組維度的元組,它也可以用于調(diào)整數(shù)組大小。
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print a.shape
輸出如下:
(2, 3)
# 這會(huì)調(diào)整數(shù)組大小
import numpy as np
a = np.array([[1,2,3],[4,5,6]]) a.shape = (3,2)
print a
輸出如下:
[[1, 2]
[3, 4]
[5, 6]]
NumPy 也提供了reshape
函數(shù)來調(diào)整數(shù)組大小。
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print b
輸出如下:
[[1, 2]
[3, 4]
[5, 6]]
ndarray.ndim
這一數(shù)組屬性返回?cái)?shù)組的維數(shù)。
# 等間隔數(shù)字的數(shù)組
import numpy as np
a = np.arange(24) print a
輸出如下:
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
# 一維數(shù)組
import numpy as np
a = np.arange(24) a.ndim
# 現(xiàn)在調(diào)整其大小
b = a.reshape(2,4,3)
print b
# b 現(xiàn)在擁有三個(gè)維度
輸出如下:
[[[ 0, 1, 2]
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
[[12, 13, 14]
[15, 16, 17]
[18, 19, 20]
[21, 22, 23]]]
numpy.itemsize
這一數(shù)組屬性返回?cái)?shù)組中每個(gè)元素的字節(jié)單位長(zhǎng)度。
# 數(shù)組的 dtype 為 int8(一個(gè)字節(jié))
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.int8)
print x.itemsize
輸出如下:
1
# 數(shù)組的 dtype 現(xiàn)在為 float32(四個(gè)字節(jié))
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.float32)
print x.itemsize
輸出如下:
4
numpy.flags
ndarray
對(duì)象擁有以下屬性。這個(gè)函數(shù)返回了它們的當(dāng)前值。
序號(hào) | 屬性及描述 |
---|---|
1. | C_CONTIGUOUS (C) 數(shù)組位于單一的、C 風(fēng)格的連續(xù)區(qū)段內(nèi) |
2. | F_CONTIGUOUS (F) 數(shù)組位于單一的、Fortran 風(fēng)格的連續(xù)區(qū)段內(nèi) |
3. | OWNDATA (O) 數(shù)組的內(nèi)存從其它對(duì)象處借用 |
4. | WRITEABLE (W) 數(shù)據(jù)區(qū)域可寫入。 將它設(shè)置為flase 會(huì)鎖定數(shù)據(jù),使其只讀 |
5. | ALIGNED (A) 數(shù)據(jù)和任何元素會(huì)為硬件適當(dāng)對(duì)齊 |
6. | UPDATEIFCOPY (U) 這個(gè)數(shù)組是另一數(shù)組的副本。當(dāng)這個(gè)數(shù)組釋放時(shí),源數(shù)組會(huì)由這個(gè)數(shù)組中的元素更新 |
下面的例子展示當(dāng)前的標(biāo)志。
import numpy as np
x = np.array([1,2,3,4,5])
print x.flags
輸出如下:
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False