使用索引数组在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.