【问题标题】:Elementwise comparison of numpy arrays to yield output arraysnumpy 数组的元素比较以产生输出数组
【发布时间】:2021-09-21 14:24:32
【问题描述】:

我们有几个类似的“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.x numpy


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 2017-01-19
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多