使用索引陣列在Numpy中構建具有環繞模式的一組選項的新陣列


使用**np.ma.choose()**方法從一組選項中構建一個新陣列。mode引數設定為'**wrap**'。如果**mode='wrap'**,大於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引數設定為'wrap'。在這裡,如果mode='wrap',大於n-1的值將對映到n-1;然後構建新的陣列:

arrRes = np.ma.choose(arr, arr_choices, mode='wrap')
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 'wrap' # if mode='wrap', 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='wrap') 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 170]

更新於:2022年2月8日

123 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.