在 Numpy 中使用索引数组从一组选项构造新数组
numpyserver side programmingprogramming更新于 2025/9/24 20:52:17
使用 Python Numpy 中的 numpy.ma.choose() 方法从一组选项构造新数组。给定一个整数数组和一个包含 n 个选项数组的列表,此方法将创建一个合并每个选项数组的新数组。如果索引中的值为 i,则新数组将在同一位置包含 choices[i] 包含的值。
choices 参数是选项数组。索引数组和所有选项应可广播到相同的形状。
mode 参数指定超出范围的索引的行为方式 −
- 'raise' : raise an error
- 'wrap' : wrap around
- 'clip' : clip to the range
步骤
首先,导入所需的库 −
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("数组...
",arr)
显示选项数组 −
print("
选项数组...
",arr_choices)
使用 choose() 方法 − 从选项集合中构造一个新的数组。
arrRes = np.ma.choose(arr, arr_choices)
第一个元素将是选项中第三个(2+1)"数组"的第一个元素。第二个元素将是第四个(3+1)选项数组的第二个元素。第三个元素将是第五个 (4+1) 选择数组的第三个元素,等等 −
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, 0])
# 显示数组
print("数组...
",arr)
# 显示 choices 数组
print("
Choices Array...
",arr_choices)
# 从集合中创建一个新数组使用 choose() 方法构造 choices 集合
arrRes = np.ma.choose(arr, arr_choices)
# 第一个元素将成为 choices 集合中第三个 (2+1) 数组的第一个元素,
# 第二个元素将成为第四个 (3+1) 数组的第二个元素,
# 第三个元素将成为第五个 (4+1) 数组的第三个元素,等等。
print("
从 choices 集合中创建新数组...
",arrRes)
输出
数组... [2 3 4 1 0] 选择数组... [[ 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 25]
相关文章
打印
下一节:从(平面)数组列表创建记录数组,并在 Numpy 中为所有数组设置有效数据类型 ❯❮ 上一节:使用 Numpy 中的 __iand__() 将掩码数组的每个元素与给定标量值进行 AND 运算

