數組索引是指在`numpy`數組中引用特定元素的方法。`numpy`的數組索引又稱為`fancy indexing`,比其他編程語言的索引強大很多。 # 1. 選取數據 numpy的索引除了像其他語言一樣選擇一個元素,還可以間隔著選取多個元素,也可以用任意的順序選取元素。 比如一維數組: ```py ...
數組索引是指在numpy
數組中引用特定元素的方法。numpy
的數組索引又稱為fancy indexing
,比其他編程語言的索引強大很多。
1. 選取數據
numpy的索引除了像其他語言一樣選擇一個元素,還可以間隔著選取多個元素,也可以用任意的順序選取元素。
比如一維數組:
arr = np.random.randint(0, 10, 5)
print(arr)
#運行結果
[7 2 6 2 1]
indexes = [0, 2, 3]
print(arr[indexes])
#運行結果
[7 6 2]
indexes = [4, 0, 2]
print(arr[indexes])
#運行結果
[1 7 6]
從上面的示例看出,通過傳入 indexes
數組,可以一次選擇多個元素。indexes
數組中的值代表數組arr
的下標,從0
開始。
對於二維數組:
arr = np.random.randint(0, 10, (5,5))
print(arr)
#運行結果
[[5 7 3 3 2]
[2 5 6 3 6]
[4 1 1 0 1]
[6 5 8 9 1]
[2 6 5 2 0]]
rows = np.array([3, 1, 4])
cols = np.array([3, 0, 1])
print(arr[rows, cols])
#運行結果
[9 2 6]
這裡 rows
和 cols
分別代表行和列的索引,從0
開始。
運行結果選取的是單個元素,分別是:arr[3, 3]
,arr[1, 0]
,arr[4, 1]
。
如果要從二維數組中通過選取行列,而不是選取單個元素的話:
arr = np.random.randint(0, 10, (5,5))
print(arr)
#運行結果
[[4 2 6 6 4]
[1 8 8 1 9]
[5 9 2 1 3]
[8 9 1 6 9]
[5 4 3 5 6]]
rows = np.array([3, 1, 4])
cols = np.array([3, 0, 1])
arr[rows[:, np.newaxis], cols]
#運行結果
[[6 8 9]
[1 1 8]
[5 5 4]]
arr[rows[:, np.newaxis], cols]
是先選取3,1,4
行,得到:
[[8 9 1 6 9]
[1 8 8 1 9]
[5 4 3 5 6]]
然後選取3,0,1
列,得到:
[[6 8 9]
[1 1 8]
[5 5 4]]
2. 與切片結合
fancy indexing
可以和之前數組的切片操作相結合:
arr = np.random.randint(0, 10, (5,5))
print(arr)
#運行結果
[[4 2 6 6 4]
[1 8 8 1 9]
[5 9 2 1 3]
[8 9 1 6 9]
[5 4 3 5 6]]
rows = np.array([3, 1, 4])
cols = np.array([3, 0, 1])
#切片在行上
print(arr[:2, cols])
#運行結果
[[6 4 2]
[1 1 8]]
#切片在列上
print(arr[rows, 1:])
#運行結果
[[9 1 6 9]
[8 8 1 9]
[4 3 5 6]]
arr[:2, cols]
先選擇前2
行,然後按照 cols
順序選擇列。arr[rows, 1:]
按照 rows
順序選擇行,然後選擇後4
列。
3. 與掩碼結合
fancy indexing
也可以和之前介紹的掩碼相結合來過濾數組:
arr = np.random.randint(0, 10, (5,5))
print(arr)
#運行結果
[[4 2 6 6 4]
[1 8 8 1 9]
[5 9 2 1 3]
[8 9 1 6 9]
[5 4 3 5 6]]
rows = np.array([3, 1, 4])
mask = np.array([True, False, False, False, True])
print(arr[rows[:, np.newaxis], mask])
#運行結果
[[8 9]
[1 9]
[5 6]]
arr[rows[:, np.newaxis], mask] 先按照 rows 的順序選擇行,然後用mask過濾掉 False 的列。
最後剩下的是 3,1,4
行的 第一列和**最後一列**
。
4. 修改數據
最後,fancy indexing
還有個重要的作用是修改數據,我們通過fancy indexing
選取數據之後,可以直接修改它們。
arr = np.random.randint(0, 10, (5,5))
print(arr)
#運行結果
[[6 4 7 8 1]
[0 3 5 0 6]
[8 9 4 7 0]
[3 0 0 9 1]
[4 5 5 0 5]]
rows = np.array([3, 1, 4])
cols = np.array([3, 0, 1])
arr[rows, cols] = [100] * len(arr[rows, cols])
print(arr)
#運行結果
[[ 6 4 7 8 1]
[100 3 5 0 6]
[ 8 9 4 7 0]
[ 3 0 0 100 1]
[ 4 100 5 0 5]]
上面的示例中,將fancy indexing
選取出的值修改為100。
註意,[100] * len(arr[rows, cols])
這個代碼是根據fancy indexing
選取出的元素個數來決定將幾個值修改成100
。
5. 總結回顧
numpy
數組索引的意義在於它可以使數組中的數據更加靈活和易於管理。
通過使用索引,開發人員可以快速訪問數組中的特定元素,而不需要遍歷整個數組。
這可以大大加快計算速度和減少記憶體使用。
此外,數組索引還可以用於數組的重構和維護。
通過對數組索引的有效使用,開發人員可以輕鬆地修改和維護數組中的數據,而不會影響到其他使用該數組的程式。