在 Numpy 中使用索引数组,通过 wrap 模式从一组选项构造一个新数组
numpyserver side programmingprogramming更新于 2025/9/26 1:22:17
使用 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("数组...
",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("
从一组选项中创建新数组...
",arrRes)
示例
import numpy as np
# 设置 choices 数组
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("数组...
",arr)
# 显示 choices 数组
print("
Choices Array...
",arr_choices)
# 从集合中创建一个新数组使用 choose() 方法构造选择集
# mode 参数设置为 'wrap'
# 如果 mode='wrap',则大于 n-1 的值将映射到 n-1;然后构造新数组
arrRes = np.ma.choose(arr, arr_choices, mode='wrap')
print("
从选择集创建新数组...
",arrRes)
输出
数组... [2 3 4 1 8] 选择数组... [[ 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]] 根据选择集合创建新数组... [100 155 210 65 170]

