使用索引数组从 NumPy 中的一组选项构建新数组
使用 Python NumPy 中的 **numpy.ma.choose()** 方法,可以根据一组选项构建一个新数组。给定一个整数数组和一个包含 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, 0])
显示数组:
print("Array...
",arr)显示选项数组:
print("
Choices Array...
",arr_choices)
使用 choose() 方法从选项集中构建新数组:
arrRes = np.ma.choose(arr, arr_choices)
第一个元素将是 choices 中第三个 (2+1) “数组” 的第一个元素。第二个元素将是第四个 (3+1) 选项数组的第二个元素。第三个元素将是第五个 (4+1) 选项数组的第三个元素,以此类推。
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, 0])
# 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
arrRes = np.ma.choose(arr, arr_choices)
# The first element will be the first element of the third (2+1) "array" in choices,
# The second element will be the second element of the fourth (3+1) choice array
# The third element will be the third element of the fifth (4+1) choice array, etc.
print("
New Array from set of choices...
",arrRes)输出
Array... [2 3 4 1 0] 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 25]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP