将布尔索引与 numpy 数组一起使用时形状不匹配

问题描述

我正在尝试使用 numpy 数组实现一个简单的算法。下面是我想要完成的一个例子。

让 a 是一个形状为 4x3 的 numpy 数组

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

设 b 是一个形状为 2x3 的布尔数组

[[ True  False False]
 [ False False  True]]

b[0,0] 为真。所以我想要 a[0:2,0] = 100

b[1,2] 为真。所以我想要一个[2:4,2] = 100

即如果 b[row,col] 为 True,我想要 a[2*row:2*(row+1),col] = 100

什么有效:

  1. 使用虚拟轴将 b 的形状从 (2x3) 更改为 (2,1,3)
  2. 将 a 从 (4x3) 重塑为 (2,2,3)。我们称之为 a_reshape
  3. a_reshape[:,0:1,:][b] = 100
  4. a_reshape[:,1:2,:][b] = 100

什么不起作用

如果我尝试同时更改两列,即

a_reshape[:,0:2,:][b] = 100

我收到以下错误

"boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1"

我可以添加 a 和 b。在这种情况下广播工作。但我无法在编制索引时进行广播。

如果有人能解释为什么会这样,我将不胜感激。 还有没有更好(更快)的方法来实现上述代码如果有任何提示,我们将不胜感激。

谢谢

"""

import numpy as np

# a is of shape 4x3
a = np.arange(0,12).reshape(4,3)

print("Original array is \n")
print(a,'\n')

# b is of shape (2,3)
b = np.random.randint(0,(2,3)) == 0

print("Indexing array is \n")
print(b,'\n')

# Change shape of b from 2x3 to 2x1x3
b = b[:,None,:]

# a_reshape is of shape (2,3)
a_reshape = a.reshape(b.shape[0],-1,a.shape[-1])

# This works
a_reshape[:,:][b] = 100
a_reshape[:,:][b] = 100
print("New array is \n")
print(a)
print("Works")

# This does not. Gives error
# boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1
print("Trying to broadcast at once array is \n")
a_reshape[:,:][b] = 100

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)