python - 形状不匹配 : indexing arrays could not be broadcast together with shapes

标签 python numpy indexing broadcast

j=np.arange(20,dtype=np.int)
site=np.ones((20,200),dtype=np.int)
sumkma=np.ones((100,20))

[sumkma[site[x],x] for x in range(20)]

这行得通,但我不想使用 for 循环。当我尝试

sumkma[site[j],j]

我收到这个错误:

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

如何修复错误?

最佳答案

当使用其他整数类型的多维数组访问 numpy 多维数组时,用于索引的数组需要具有相同的形状。

如果可能的话,Numpy 会很高兴地广播 - 但要做到这一点,数组需要具有相同的维度,例如这有效:

sumkma[site[j], j[:,np.newaxis]]

np.newaxis 导致 j[:,np.newaxis] 是二维的(形状现在是 (20,1),而 j 的形状是一维 (20,))。它现在有一个可以广播到 site[j] 的形状:

>>> j.shape
(20,)
>>> site[j].shape
(20,200)
>>> j[:,np.newaxis].shape
(20,1)

索引数组的相同维度允许 numpy 广播它们具有相同的形状 (20,200)

https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html#indexing-multi-dimensional-arrays

关于python - 形状不匹配 : indexing arrays could not be broadcast together with shapes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46124469/

相关文章:

arrays - 优雅高效的 Numpy 数组运算 - np.linspace

python - 如何使用索引更新张量的元素?

arrays - 在 MATLAB 中从数组中选择元素

python - 如果我说 x = x 会发生什么? (在较低的编译器级别)

python - 计算温度的偏导数(温度的水平平流)

Python Txt 文件替换 - 'str' 对象不支持项目分配

python - 霍夫圆检测AttributeError : 'NoneType' object has no attribute 'rint'

python - 根据另一个 DataFrame 选择一个 DataFrame 的列

python - tqdm.auto 进度条显示不正确,而是显示 HBox(children=(FloatProgress(value=0.0), HTML(value ='' )))

python - 你可以使用 wxPython 自动隐藏框架/对话框吗?