[NumPy 學習筆記] - No.2 NumPy數據索引

numpy學習筆記

numpy是python中非常有用的一個庫,我們可以使用numpy創建大型的高維數組並進行運算。這裏記錄一下numpy一些常用的方法。如果想仔細研究numpy的強大功能還需要翻閱NumPy API文檔

數組索引

常見索引

對數組最簡單的索引就是常見的[]索引

#  索引
x = np.array([1, 2, 3])
print ("x[0]: ", x[0]) # x[0]:  1
x[0] = 0
print ("x: ", x) # x:  [0 2 3]

y = np.arange(6).reshape(2,-1)  
print("y:\n",y) # [[0 1 2]
				# [3 4 5]]
print(y[1][1])  # 4
切片索引

在python中,我們使用切片來訪問list;在NumPy中,也可以使用切片訪問numpy

訪問某一行/列:

y = np.arange(6).reshape(2,-1) 
print("y:\n",y) # [[0 1 2]
				# [3 4 5]]
    
print("row 0:",y[0,:])  # row 0: [0 1 2] 
print("column 2:",y[:,2]) # column 2: [2 5]

訪問數組中的某一塊數據:

print("row 0,1 & cols 1,2:\n",y[0:2,1:3])

row 0,1 & cols 1,2:
[[1 2]
[4 5]]

數組索引

在numpy中還可以使用數組進行索引:

t = np.arange(12).reshape(3,-1)
print("t :\n",t)
rows = [0,1,2]
cols = [0,3,1]

print("index values:\n",t[rows,cols])

t :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
index values:
[0 7 9]

在上邊的例子中,我們定義了一個3x4的矩陣,然後訪問 [0][0], [1][3], [2][1]三個位置的數據。

布爾數組索引

在numpy中,我們還可以很輕鬆的查看,某些滿足布爾條件的元素集合。示例如下:

在python中, x>2 代表一個布爾表達式,用於判斷x是否大於二,返回True或者False;如果x是一個numpy的數組,將返回什麼結果呢?

# Boolean array indexing
x = np.array([[1,2], [3, 4], [5, 6]])
bool_index = x > 2
print ("x:\n", x)
print ("x > 2:\n", bool_index)

x:
[[1 2]
[3 4]
[5 6]]
x > 2:
[[False False]
[ True True]
[ True True]]

可以看到,x > 2 返回了bool類型的numpy數組,該數組中每個元素是原數組中對應位置 針對 x > 2條件的結果。

Numpy中的布爾索引就是將布爾數組應用到numpy數組中;布爾數組中的True表示選取被索引數組對應位置的值,False則表示不選取對應位置的值。因此我們可以很簡單的獲取到,某個數組中所有大於2的元素的集合。

print ("x[x > 2]:\n", x[x > 2])

x[x > 2]:
[3 4 5 6]

資料參考:practicalAI

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章