使用索引陣列從 NumPy 中的一組選項構建新陣列
使用 Python NumPy 中的 **numpy.ma.choose()** 方法,可以根據一組選項構建一個新陣列。給定一個整數陣列和一個包含 n 個選項陣列的列表,此方法將建立一個新陣列,該數組合並了每個選項陣列。當索引中的值為 i 時,新陣列將具有 choices[i] 在相同位置包含的值。
choices 引數是選項陣列。索引陣列和所有選項都應該可以廣播到相同的形狀。
mode 引數指定了越界索引的行為:
- 'raise':引發錯誤
- 'wrap':迴圈
- 'clip':裁剪到範圍
步驟
首先,匯入所需的庫:
import numpy as np
設定選項陣列:
arr_choices = np.array([[5, 10, 15, 20, 25], [50, 55, 60, 65, 70], [100, 105, 110, 115, 120], [150, 155, 160, 165, 170], [200, 205, 210, 215, 220]])
建立一個新陣列:
arr = np.array([2, 3, 4, 1, 0])
顯示陣列:
print("Array...
",arr)顯示選項陣列:
print("
Choices Array...
",arr_choices)
使用 choose() 方法從選項集中構建新陣列:
arrRes = np.ma.choose(arr, arr_choices)
第一個元素將是 choices 中第三個 (2+1) “陣列” 的第一個元素。第二個元素將是第四個 (3+1) 選項陣列的第二個元素。第三個元素將是第五個 (4+1) 選項陣列的第三個元素,以此類推。
print("
New Array from set of choices...
",arrRes)
示例
import numpy as np
# set choices array
arr_choices = np.array([[5, 10, 15, 20, 25], [50, 55, 60, 65, 70], [100, 105, 110, 115, 120], [150, 155, 160, 165, 170], [200, 205, 210, 215, 220]])
# Create a new array
arr = np.array([2, 3, 4, 1, 0])
# Displaying the array
print("Array...
",arr)
# Displaying the choices array
print("
Choices Array...
",arr_choices)
# A new array from the set of choices is constructed using the choose() method
arrRes = np.ma.choose(arr, arr_choices)
# The first element will be the first element of the third (2+1) "array" in choices,
# The second element will be the second element of the fourth (3+1) choice array
# The third element will be the third element of the fifth (4+1) choice array, etc.
print("
New Array from set of choices...
",arrRes)輸出
Array... [2 3 4 1 0] Choices Array... [[ 5 10 15 20 25] [ 50 55 60 65 70] [100 105 110 115 120] [150 155 160 165 170] [200 205 210 215 220]] New Array from set of choices... [100 155 210 65 25]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP