Numpy之N維數組-ndarray
1 ndarray的屬性
數組屬性反映了數組本身固有的資訊。
屬性名字 | 屬性解釋 |
---|---|
ndarray.shape | 數組次元的元組 【假如是8行5列的數組,将會傳回(8,5)】 |
ndarray.ndim | 數組維數 【假如是二維數組,将會傳回2】 |
ndarray.size | 數組中的元素數量 【如果是8行5列,将會傳回40】 |
ndarray.itemsize | 一個數組元素的長度(位元組) 【如果元素是(整型)數字,将會傳回8】 |
ndarray.dtype | 數組元素的類型 【整型的話,傳回:dtype('int64'),有的電腦可能是32】 |
2 ndarray的形狀
首先建立一些數組。
# 建立不同形狀的數組
import numpy as np
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]]])
分别列印出形狀:
如何了解數組的形狀?
二維數組:
三維數組:
【類似于excel中有多個sheet】
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 | 數組元素的類型 |