首页 > 解决方案 > Numpy:在其他布尔数组的“真”上覆盖布尔数组

问题描述

我有一个 bool 2D 数组 A,其中 True 的数字是 bool 2D 数组 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 ]]

提前致谢。

标签: arraysnumpyindexingbooleanboolean-indexing

解决方案


# 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

推荐阅读