2-N維陣列-ndarray
阿新 • • 發佈:2021-06-21
學習目標
- 目標
- 說明陣列的屬性,形狀、型別
1 ndarray的屬性
陣列屬性反映了陣列本身固有的資訊。
屬性名字 | 屬性解釋 |
---|---|
ndarray.shape | 陣列維度的元組 |
ndarray.ndim | 陣列維數 |
ndarray.size | 陣列中的元素數量 |
ndarray.itemsize | 一個數組元素的長度(位元組) |
ndarray.dtype | 陣列元素的型別 |
2 ndarray的形狀
首先建立一些陣列。
# 建立不同形狀的陣列 >>> a = np.array([[1,2,3],[4,5,6]]) >>> b = np.array([1,2,3,4]) >>> c = np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
分別打印出形狀
>>> a.shape
>>> b.shape
>>> c.shape
(2, 3) # 二維陣列
(4,) # 一維陣列
(2, 2, 3) # 三維陣列
如何理解陣列的形狀?
二維陣列:
三維陣列:
3 ndarray的型別
>>> type(score.dtype)
<type 'numpy.dtype'>
dtype是numpy.dtype型別,先看看對於陣列來說都有哪些型別
名稱 | 描述 | 簡寫 |
---|---|---|
np.bool | 用一個位元組儲存的布林型別(True或False) | 'b' |
np.int8 | 一個位元組大小,-128 至 127 | 'i' |
np.int16 | 整數,-32768 至 32767 | 'i2' |
np.int32 | 整數,-2^31 至 2^32 -1 | 'i4' |
np.int64 | 整數,-2^63 至 2^63 - 1 | 'i8' |
np.uint8 | 無符號整數,0 至 255 | 'u' |
np.uint16 | 無符號整數,0 至 65535 | 'u2' |
np.uint32 | 無符號整數,0 至 2^32 - 1 | 'u4' |
np.uint64 | 無符號整數,0 至 2^64 - 1 | 'u8' |
np.float16 | 半精度浮點數:16位,正負號1位,指數5位,精度10位 | 'f2' |
np.float32 | 單精度浮點數:32位,正負號1位,指數8位,精度23位 | 'f4' |
np.float64 | 雙精度浮點數:64位,正負號1位,指數11位,精度52位 | 'f8' |
np.complex64 | 複數,分別用兩個32位浮點數表示實部和虛部 | 'c8' |
np.complex128 | 複數,分別用兩個64位浮點數表示實部和虛部 | 'c16' |
np.object_ | python物件 | 'O' |
np.string_ | 字串 | 'S' |
np.unicode_ | unicode型別 | 'U' |
建立陣列的時候指定型別
>>> a = np.array([[1, 2, 3],[4, 5, 6]], dtype=np.float32)
>>> a.dtype
dtype('float32')
>>> arr = np.array(['python', 'tensorflow', 'scikit-learn', 'numpy'], dtype = np.string_)
>>> arr
array([b'python', b'tensorflow', b'scikit-learn', b'numpy'], dtype='|S12')
- 注意:若不指定,整數預設int64,小數預設float64
4 總結
陣列的基本屬性【知道】
屬性名字 | 屬性解釋 |
---|---|
ndarray.shape | 陣列維度的元組 |
ndarray.ndim | 陣列維數 |
ndarray.size | 陣列中的元素數量 |
ndarray.itemsize | 一個數組元素的長度(位元組) |
ndarray.dtype | 陣列元素的型別 |