【问题标题】:Numpy: Overlay Boolean Array on "True"s of other boolean arrayNumpy:在其他布尔数组的“真”上覆盖布尔数组
【发布时间】:2020-06-07 06:09:39
【问题描述】:

我有一个 bool 二维数组 A,其中 True 的数字是 bool 二维数组 B 的维数。

A = np.array([[False, True, True, False, True],[False, False, False, False, False],[False, True, True, False, True]])
B = np.array([[True, False, True],[True, True, True]])

A =[[False, True,  True,  False, True],
    [False, False, False, False, False],
    [False, True,  True,  False, True]]
B =[[True, False, True],
    [True, False, True]]

我想在 A 的“真”数组上“叠加”B,这样我就可以得到

C =  
[[False, **True**,  **False**,  False, **True**],  
[False, False, False, False, False],  
[False, **True**,  **False**,  False, **True**]]  

我的最终目标是操作一个数组

arr = [[1, 2, 3, 4, 5], [6,7,8,9,10] , [11, 12, 13、14、15]]

类似的东西

arr[A] = arr[A] + B*2

得到

arr = [[1, 4, 3, 4, 7], [6,7,8,9,10] , [11, 14, 13、14、17]]

提前致谢。

【问题讨论】:

    标签: arrays numpy indexing boolean boolean-indexing


    【解决方案1】:
    # get the indexes that are True
    Xi = np.nonzero(A)
    
    # convert to an array of 1D
    B1 = np.ndarray.flatten(B)
    
    # use Xi for dynamic indexing
    A[Xi]=B1
    

    【讨论】:

      【解决方案2】:

      我想出的解决方案是(仅当 B 是二次方时才有效):

      arr[A] = (arr[A].reshape(len(B), len(B)) + 2 * B).ravel()
      

      【讨论】:

        猜你喜欢
        • 2016-12-08
        • 2016-03-11
        • 2020-10-23
        • 2013-08-07
        • 1970-01-01
        • 2018-08-10
        • 2021-01-06
        • 2014-10-20
        • 2017-09-24
        相关资源
        最近更新 更多