python-3.x - numpy 数组的元素比较以产生输出数组
问题描述
我们有几个“in_arrays”,比如
in_1=np.array([0.4,0.7,0.8,0.3])
in_2=np.array([0.9,0.8,0.6,0.4])
我需要创建两个输出,例如
out_1=np.array([0,0,1,0])
out_2=np.array([1,1,0,0])
因此,如果相应输入数组中的值大于 0.5 并且该输入数组的该位置的值大于该位置的其他数组的值,则输出数组的给定元素为 1。这样做的有效方法是什么?
解决方案
您可以将所有输入数组聚合到一个矩阵中,其中每一行代表一个特定的输入数组。这样就可以将所有输出数组再次计算为单个矩阵。
代码可能看起来像这样:
import numpy as np
# input matrix corresponding to the example input arrays given in the question
in_matrix = np.array([[0.4,0.7,0.8,0.3], [0.9,0.8,0.6,0.4]])
out_matrix = np.zeros(in_matrix.shape)
# each element in the array is the maximal value of the corresponding column in input_matrix
max_values = np.max(in_matrix, axis=0)
# compute the values in the output matrix row by row
for n, row in enumerate(in_matrix):
out_matrix[n] = np.logical_and(row > 0.5, row == max_values)
推荐阅读
- python - 如何将函数/方法应用于多个变量?
- android - 在使用 Unity 3D 开发的 Android App 中使用 Open Weather Map API
- scala - 无法用整数值替换 Spark Dataframe 中的空值
- express - 如何在不重新加载页面的情况下选择 id 时获取数据
- reactjs - 我如何做嵌套路由器?
- swiftui - LineChart 在 Xcode 11.1 和 11.2 beta 中不起作用
- python - 覆盖 BaseForm 类的 init 方法后 ChoiceField 消失
- system - 使公平损失可靠
- node.js - Node.js 使用 Jest 捕获异步错误
- javascript - 使用 Redux 数据持久化 Material-UI 选择