【问题标题】:How to apply mask from array to another matrix in numpy如何将数组中的掩码应用于numpy中的另一个矩阵
【发布时间】:2018-03-28 14:43:57
【问题描述】:

我如何在 numpy 中应用掩码来获得此输出?

ar2 = np.arange(1,26)[::-1].reshape([5,5]).T
ar3 = np.array([1,1,-1,-1,1])
print ar2, '\n\n',  ar3

[[25 20 15 10  5]
 [24 19 14  9  4]
 [23 18 13  8  3]
 [22 17 12  7  2]
 [21 16 11  6  1]] 

[ 1  1 -1 -1  1]

--apply where ar3 = 1: ar2/ar2[:,0][:, np.newaxis]

--apply where ar3 = -1: ar2/ar2[:,4][:, np.newaxis]

我追求的结果是:

[[1 0 0 0 0]
 [1 0 0 0 0]
 [ 7  6  4  2  1]
 [11  8  6  3  1]
 [1 0 0 0 0]]

我试过np.where()

【问题讨论】:

    标签: python arrays pandas numpy


    【解决方案1】:

    我不明白为什么 np.where 不应该在这里工作:

    >>> np.where((ar3==1)[:, None], 
    ...          ar2 // ar2[:, [0]],  # where condition is True, divide by first column
    ...          ar2 // ar2[:, [4]])  # where condition is False, divide by last column
    array([[ 1,  0,  0,  0,  0],
           [ 1,  0,  0,  0,  0],
           [ 7,  6,  4,  2,  1],
           [11,  8,  6,  3,  1],
           [ 1,  0,  0,  0,  0]])
    

    我使用的是 Python 3,这就是为什么我使用 //(地板除法)而不是常规除法(/),否则结果将包含浮点数。

    这会急切地计算数组,因此它会评估 ar2 // ar2[:, [0]] ar2 // ar2[:, [4]] 的所有值。在内存中有效地保存了 3 个大小为 ar2 的数组(结果和两个临时数组)。如果您希望它更节省内存,则需要在执行操作之前应用掩码:

    >>> res = np.empty_like(ar2)
    >>> mask = ar3 == 1
    >>> res[mask] = ar2[mask] // ar2[mask][:, [0]]
    >>> res[~mask] = ar2[~mask] // ar2[~mask][:, [4]]
    >>> res
    array([[ 1,  0,  0,  0,  0],
           [ 1,  0,  0,  0,  0],
           [ 7,  6,  4,  2,  1],
           [11,  8,  6,  3,  1],
           [ 1,  0,  0,  0,  0]])
    

    这仅计算使用较少内存的必要值(并且可能也更快)。

    【讨论】:

      【解决方案2】:

      不是最优雅的,但这是我能想到的。

      m = ar3 == -1
      a = (ar2 // ar2[:, [0]])
      a[m] = (ar2 // ar2[:, [4]])[m]
      
      print(a)
      array([[ 1,  0,  0,  0,  0],
             [ 1,  0,  0,  0,  0],
             [ 7,  6,  4,  2,  1],
             [11,  8,  6,  3,  1],
             [ 1,  0,  0,  0,  0]], dtype=int32)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 2020-02-24
        相关资源
        最近更新 更多