Skip to main content
 首页 » 编程设计

python之通过另一个数组的属性选择二维数组的几个部分

2025年04月02日13sxdcgaq8080

这是我的问题。

  • a 是一个 100x100 形状的二维 numpy 数组,包含有限的数字

  • b 是一个 100x100 形状的二维 bool 数组,包含 True 和 False

我的目标:

Select specific part of array a when the value of b[i,j] == True

我的代码在这里:

 select = a[np.array(np.where(b == True)).T]   

但是结果显示有些索引超出了边界。

有人有什么想法可以实现吗?

请您参考如下方法:

那是因为你在转置索引数组。此外,您不需要将 np.where() 的结果转换为 numpy 数组,只需将其作为索引传递给第一个数组即可。

这是一个例子:

>>> b = np.random.choice([0, 1], size=(10,10)) 
>>> b 
array([[0, 0, 0, 1, 0, 1, 1, 0, 0, 0], 
       [0, 1, 1, 0, 0, 0, 0, 1, 1, 1], 
       [1, 1, 1, 1, 1, 0, 0, 0, 1, 0], 
       [1, 1, 0, 1, 0, 0, 1, 0, 0, 1], 
       [0, 1, 0, 0, 1, 1, 1, 1, 1, 1], 
       [1, 1, 1, 1, 1, 1, 0, 1, 0, 0], 
       [0, 1, 1, 1, 0, 0, 0, 0, 0, 0], 
       [0, 1, 0, 0, 1, 1, 1, 0, 0, 1], 
       [1, 0, 1, 0, 0, 1, 0, 1, 0, 0], 
       [1, 0, 0, 1, 0, 1, 1, 0, 0, 1]]) 
>>> a = np.random.choice(100, size=(10,10)) 
>>>  
>>> a 
array([[47, 90, 94, 11, 17, 65, 95, 57, 36, 43], 
       [65, 82, 37, 93, 65, 32,  8, 47, 16, 12], 
       [66, 60, 40, 90, 34, 30, 40,  2, 36, 65], 
       [ 8, 53, 69,  0, 61, 60, 94, 37, 77, 43], 
       [59, 47, 21, 93, 58,  0, 92, 26, 17, 44], 
       [98, 16, 33, 56, 39, 30, 14, 93, 93, 58], 
       [96, 40, 35, 17, 21, 70, 26,  0, 21, 81], 
       [47,  4, 20, 82, 19, 89, 50, 26, 38,  4], 
       [60,  3, 72, 56, 78, 55, 60, 53,  3, 87], 
       [80,  1, 65,  2, 92, 92, 97, 17, 55, 67]]) 
 
>>> a[np.where(b)] 
array([11, 65, 95, 82, 37, 47, 16, 12, 66, 60, 40, 90, 34, 36,  8, 53,  0, 
       94, 43, 47, 58,  0, 92, 26, 17, 44, 98, 16, 33, 56, 39, 30, 93, 40, 
       35, 17,  4, 19, 89, 50,  4, 60, 72, 55, 53, 80,  2, 92, 97, 67]) 

请注意,您不必使用 b==True 作为 np.where 条件,当您传递 bool 数组时,它将选择确定的有效项目通过 python 的 Truth Value Testing .