numpy数组与其他数组建立索引会产生广播错误 [英] Numpy array Indexing with other arrays yields broadcasting error

查看:87
本文介绍了numpy数组与其他数组建立索引会产生广播错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个索引数组。

elim=range(130,240)
tlim=range(0,610)

要索引的数组 I 的原始形状为(299,3800)

The array to be indexed, I, has originally shape of (299, 3800)

当我尝试按以下方式对其编制索引

When I try to index it as follow

I[elim,tlim]

我收到以下错误消息。


形状不匹配:索引数组无法与形状(110,)(610,)一起广播

shape mismatch: indexing arrays could not be broadcast together with shapes (110,) (610,)

我没有不要指望这种错误。有人可以解释这里发生了什么吗?

I didn't expect such errors. Could someone explain what is happening here?

谢谢!

推荐答案

让我们重现示例并具有指定形状的随机数组:

Let's reproduce the example with a random array of the specified shape:

elim=range(0,610)
tlim=range(130,240)
a = np.random.rand(299, 3800)

a[tlim, elim]



IndexError:形状不匹配:索引数组无法与形状(110,)(610,)一起广播

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

因为您使用整数索引数组对数组进行索引,因此高级索引规则将适用。
在此示例中应使用切片

This raises an error because you're using arrays of integer indexes to index the array, and hence advanced indexing rules will apply. You should use slices for this example

a[130:240,0:610].shape
# (110, 610)

请参见理解切片符号(NumPy索引只是对n维数组的同一概念的扩展。

See Understanding slice notation (NumPy indexing, is just an extension of the same concept up to ndimensional arrays.

对于具有索引列表的情况,不一定表示为切片,您有 np.ix _ 。有关numpy索引的更多信息,请可能有帮助

For the cases in which you have a list of indices, not necessarily expressable as slices, you have np.ix_. For more on numpy indexing, this might help

a[np.ix_(tlim, elim)].shape
# (110, 610)

这篇关于numpy数组与其他数组建立索引会产生广播错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆