使用索引陣列從 NumPy 中的一組選項中構建一個新的陣列,並使用裁剪模式
使用 **np.ma.choose()** 方法從一組選項中構建一個新的陣列。mode 引數設定為 '**clip**'。如果 **mode='clip'**,則大於 n-1 的值將對映到 n-1;然後構建新的陣列。
給定一個整數陣列和一個包含 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, 8])
顯示陣列 -
print("Array...
",arr)顯示選項陣列 -
print("
Choices Array...
",arr_choices)使用 choose() 方法從一組選項中構建一個新的陣列。mode 引數設定為 'clip'。這裡,如果 mode='clip',則大於 n-1 的值將對映到 n-1;然後構建新的陣列。
arrRes = np.ma.choose(arr, arr_choices, mode='clip')
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, 8])
# 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
# The mode parameter is set to 'clip'
# if mode='clip', values greater than n-1 are mapped to n-1; and then the new array is constructed
arrRes = np.ma.choose(arr, arr_choices, mode='clip')
print("
New Array from set of choices...
",arrRes)輸出
Array... [2 3 4 1 8] 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 220]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP