gpt4 book ai didi

python - 索引错误 : shape mismatch: indexing arrays could not be broadcast together with shapes

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:01 28 4
gpt4 key购买 nike

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:形状不匹配:索引数组无法与形状 (3,) (4,) (3,4) 一起广播

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

最佳答案

尝试:

>>> 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,:]

另类风格

如果有人愿意,我们可以用 np.newaxis 替换 None:

>>> 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似乎有效。)

关于python - 索引错误 : shape mismatch: indexing arrays could not be broadcast together with shapes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858600/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com