使用索引数组从 NumPy 中的一组选项中构建一个新的数组,并使用裁剪模式
使用 **np.ma.choose()** 方法从一组选项中构建一个新的数组。mode 参数设置为 '**clip**'。如果 **mode='clip'**,则大于 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 参数设置为 'clip'。这里,如果 mode='clip',则大于 n-1 的值将映射到 n-1;然后构建新的数组。
arrRes = np.ma.choose(arr, arr_choices, mode='clip')
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 'clip'
# if mode='clip', 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='clip')
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 220]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP