【问题标题】:IndexError: shape mismatch: indexing arrays could not be broadcast together with shapesIndexError:形状不匹配:索引数组无法与形状一起广播
【发布时间】:2018-07-29 05:47:48
【问题描述】:
a=np.arange(240).reshape(3,4,20)
b=np.arange(12).reshape(3,4)
c=np.zeros((3,4),dtype=int)
x=np.arange(3)
y=np.arange(4)

我想通过以下步骤获得一个 2d (3,4) 形状数组,无需循环。

for i in x:
    c[i]=a[i,y,b[i]]
c
array([[  0,  21,  42,  63],
       [ 84, 105, 126, 147],
       [168, 189, 210, 231]])

我试过了,

c=a[x,y,b]

但它显示

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (4,) (3,4)

然后我也尝试通过[:,None]建立newaxis,还是不行。

【问题讨论】:

  • "我也尝试通过 [:,None] 建立 newaxis,它也不起作用。"始终发布您尝试的确切内容,因为这种方法(如果正确完成)按照下面的答案工作......
  • 你想要一个 (3,4),而b 就是这个形状。其他索引必须广播到相同的形状。

标签: python arrays numpy indexing array-broadcasting


【解决方案1】:

试试:

>>> a[x[:,None], y[None,:], b]
array([[  0,  21,  42,  63],
       [ 84, 105, 126, 147],
       [168, 189, 210, 231]])

讨论

你试过a[x,y,b]。注意错误信息:

>>> a[x, y, b]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast
            together with shapes (3,) (4,) (3,4) 

(3,) 表示我们需要扩展x 以将 3 作为第一个维度,将 4 作为第二个维度。我们通过指定x[:,None] 来做到这一点(这实际上允许x 被广播到任何大小的第二维)。

同样,错误消息显示我们需要将y 映射到形状(3,4),而我们使用y[None,:] 来做到这一点。

另类风格

如果愿意,我们可以将None 替换为np.newaxis:

>>> a[x[:,np.newaxis], y[np.newaxis,:], b]
array([[  0,  21,  42,  63],
       [ 84, 105, 126, 147],
       [168, 189, 210, 231]])

np.newaxis 为无:

>>> np.newaxis is None
True

(如果我没记错的话,numpy 的一些早期版本对newaxis 使用了不同的大写样式。不过,对于所有版本,None 似乎都有效。)

【讨论】:

    【解决方案2】:

    相似但不同,硬编码不是通用的。

    >>> b = np.ravel(a)[np.arange(0,240,21)]
    >>> b.reshape((3,4))
    array([[  0,  21,  42,  63],
           [ 84, 105, 126, 147],
           [168, 189, 210, 231]])
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-17
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2021-07-20
      • 2021-05-22
      相关资源
      最近更新 更多