首页 > 解决方案 > 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。这样做的有效方法是什么?

标签: python-3.xnumpy

解决方案


您可以将所有输入数组聚合到一个矩阵中,其中每一行代表一个特定的输入数组。这样就可以将所有输出数组再次计算为单个矩阵。

代码可能看起来像这样:

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)

推荐阅读