在 NumPy 中,神奇索引(Fancy Indexing)?和?布爾索引(Boolean Indexing)?是兩種強大的索引方式,用于從數組中提取特定元素或子集。以下是它們的詳細說明和示例:
1.?神奇索引(Fancy Indexing)
-
定義:通過傳遞一個整數數組或列表來索引數組,返回指定位置的元素。
-
特點:
- 索引數組可以是任意形狀。
- 返回的結果形狀與索引數組一致。
-
示例:
-
import numpy as np array = np.array([10, 20, 30, 40, 50]) indices = [1, 3, 4] # 指定索引位置 result = array[indices] # 提取對應位置的元素 print(result) # 輸出: [20 40 50]
-
多維數組示例:
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) row_indices = [0, 1, 2] col_indices = [1, 0, 2] result = matrix[row_indices, col_indices] # 提取 (0,1), (1,0), (2,2) 位置的元素 print(result) # 輸出: [2 4 9]
2.?布爾索引(Boolean Indexing)
-
定義:通過傳遞一個布爾數組來索引數組,返回滿足條件的元素。
-
特點:
- 布爾數組必須與目標數組形狀一致。
- 返回的結果是一維數組。
-
示例:
array = np.array([10, 20, 30, 40, 50]) condition = array > 30 # 創建布爾條件 result = array[condition] # 提取滿足條件的元素 print(result) # 輸出: [40 50]
-
多維數組示例:
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) condition = matrix > 5 # 創建布爾條件 result = matrix[condition] # 提取滿足條件的元素 print(result) # 輸出: [6 7 8 9]
3.?神奇索引與布爾索引的區別
特性 | 神奇索引(Fancy Indexing) | 布爾索引(Boolean Indexing) |
---|---|---|
索引類型 | 整數數組或列表 | 布爾數組 |
結果形狀 | 與索引數組一致 | 一維數組 |
適用場景 | 提取指定位置的元素 | 提取滿足條件的元素 |
多維數組支持 | 支持,通過指定行列索引 | 支持,返回滿足條件的所有元素 |
4.?應用場景
- 神奇索引:
- 提取特定位置的元素。
- 重新排列數組。
- 布爾索引:
- 過濾滿足條件的元素。
- 數據清洗和預處理。
5.?注意事項
- 神奇索引:索引數組的值必須在數組的合法范圍內,否則會拋出?
IndexError
。 - 布爾索引:布爾數組必須與目標數組形狀一致,否則會拋出?
IndexError
。
示例代碼總結
import numpy as np # 神奇索引
array = np.array([10, 20, 30, 40, 50])
indices = [1, 3, 4]
result_fancy = array[indices] # 輸出: [20 40 50]# 布爾索引
condition = array > 30
result_boolean = array[condition] # 輸出: [40 50]