numpy是python中的一個數值計算的開源庫,主要用來存儲和處理多維數組,核心數據結構是ndarray。本文分享ndarray的基本使用, 首先需要安裝numpy
pip install numpy
二維ndarray要構造二維數組(就是矩陣),需要知道數組的行數、列數和每個元素的數據類型,在numpy中,常見的有uint8、int32、float32、float64等等
下面構造一個2行3列全是0的uint8類型的二維數組
(base) xugaoxiang@1070Ti:~$ ipython
Python 3.7.6 (default, Jan 8 2020, 19:59:22)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import numpy as np
In [2]: np.zeros((2, 3), np.uint8)
Out[2]:
array([[0, 0, 0],
[0, 0, 0]], dtype=uint8)
In [3]:如果想構造全是1的數組,可以使用np.ones()方法
In [5]: np.ones((2, 3), np.uint8)
Out[5]:
array([[1, 1, 1],
[1, 1, 1]], dtype=uint8)使用常量數據進行初始化
In [8]: np.array([[1, 2, 3], [4, 5, 6]], np.float64)
Out[8]:
array([[1., 2., 3.],
[4., 5., 6.]])
三維ndarray三維數組可以理解為每一個元素都是一個二維數組。比如一個2x2x3的uint8三維數組,就是2個2x3的二維數組
In [11]: np.array([[[1, 2, 3], [4, 5, 6]], [[9, 8, 7], [6, 5, 4]]], np.uint8)
Out[11]:
array([[[1, 2, 3],
[4, 5, 6]],
[[9, 8, 7],
[6, 5, 4]]], dtype=uint8)
In [12]:了解了這個原理後,以此類推,更高維的數組就很好理解了
ndarray的常用屬性及元素值獲取shape屬性可以獲取到尺寸,比如
In [12]: t = np.zeros([2, 3], np.uint8)
In [13]: t.shape
Out[13]: (2, 3)
In [14]:
In [14]: t3 = np.array([[[1, 2, 3], [4, 5, 6]], [[9, 8, 7], [6, 5, 4]]],np.uint8
...: )
In [15]: t3.shape
Out[15]: (2, 2, 3)
In [16]:dtype屬性可以獲取到元素的數據類型,如
In [17]: t.dtype
Out[17]: dtype('uint8')
In [18]: t3.dtype
Out[18]: dtype('uint8')
In [19]:獲取數組中某個元素的值,可以通過索引來獲取,索引從0開始計算,以二維為例
In [20]: t = np.array([[1, 2, 3], [4, 5, 6]], np.uint8)
In [21]: t[1, 1]
Out[21]: 5
In [22]: t[0, 2]
Out[22]: 3
In [23]:獲取某行數據,以上面的t變量為例,代碼如下
In [36]: t[0,:]
Out[36]: array([1, 2, 3], dtype=uint8)
In [37]: t[1,:]
Out[37]: array([4, 5, 6], dtype=uint8)
# 當索引超出後,會報錯
In [38]: t[2,:]
IndexError Traceback (most recent call last)
<ipython-input-38-79ac94a5bef6> in <module>
----> 1 t[2,:]
IndexError: index 2 is out of bounds for axis 0 with size 2
In [39]:獲取某列數據,以上面的t變量為例,代碼如下
In [40]: t[:,0]
Out[40]: array([1, 4], dtype=uint8)
In [41]: t[:,1]
Out[41]: array([2, 5], dtype=uint8)
In [42]: t[:,2]
Out[42]: array([3, 6], dtype=uint8)
In [43]: t[:,3]
IndexError Traceback (most recent call last)
<ipython-input-43-cd95ba35026b> in <module>
----> 1 t[:,3]
IndexError: index 3 is out of bounds for axis 1 with size 3
In [44]:除此之外,還可以獲取到某一區間,代碼如下
# 這裡的區間操作是左閉右開的,如[0:1],就是從0行開始,但不包括第1行
In [45]: t[0:1,1:3]
Out[45]: array([[2, 3]], dtype=uint8)
In [46]: