多个维度中的numpy数组整数索引 [英] numpy array integer indexing in more than one dimension

查看:305
本文介绍了多个维度中的numpy数组整数索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很确定我缺少整数索引的东西,可以使用一些帮助.假设我创建了一个2D数组:

I'm pretty sure I'm missing something with integer indexing and could use some help. Say that I create a 2D array:

>>> import numpy as np
>>> x=np.array(range(24)).reshape((4,6))
>>> x
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])

然后我可以选择第1行和第2行:

I can then select row 1 and 2 with:

>>> x[[1,2],:]
array([[ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])

或第2行和第3行的第1列带有:

Or the column 1 of rows 2 and 3 with:

>>> x[[1,2],1]
array([ 7, 13])

因此,我可以选择第1行和第2行的第3、4和5列,这对我来说很有意义:

So it would makes sense to me that I can select columns 3, 4 and 5 of rows 1 and 2 with this:

>>> x[[1,2],[3,4,5]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape

相反,我需要分两个步骤进行操作:

And instead I need to do it in two steps:

>>> a=x[[1,2],:]
>>> a
array([[ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])
>>> a[:,[3,4,5]]
array([[ 9, 10, 11],
       [15, 16, 17]])

来自R,我的期望似乎是错误的.您是否可以一步一步确认这确实是不可能的,或者提出更好的选择?谢谢!

Coming from R, my expectations seem to be wrong. Can you confirm that this is indeed not possible in one step, or suggest a better alternative? Thanks!

请注意,我在示例中对行和列的选择恰好是连续的,但不必如此.换句话说,切片索引无法满足我的情况.

please note my choice of rows and columns in the example happen to be consecutive, but they don't have to be. In other words, slice indexing won't do for my case.

推荐答案

您还可以选择在索引数组之间使用广播,这是我通常要做的,而不是两次索引,从而创建您的中间副本数据:

You also have the option of using broadcasting among the indexing arrays, which is what I would normally do, rather than indexing twice, which creates an intermediate copy of your data:

>>> x[[[1], [2]],[[3, 4, 5]]]
array([[ 9, 10, 11],
       [15, 16, 17]])

要更好地了解正在发生的事情以及如何处理大量索引:

To see a little better what is going on and how to handle larger numbers of indices:

>>> row_idx = np.array([1, 2])
>>> col_idx = np.array([3, 4, 5])
>>> x[row_idx.reshape(-1, 1), col_idx]
array([[ 9, 10, 11],
       [15, 16, 17]])

这篇关于多个维度中的numpy数组整数索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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