I've been going crazy trying to figure out what stupid thing I'm doing wrong here.
我一直想弄明白我做错了什么蠢事。
I'm using NumPy, and I have specific row indices and specific column indices that I want to select from. Here's the gist of my problem:
我使用NumPy,我有特定的行索引和特定的列索引,我想从中选择。下面是我的问题的要点:
import numpy as np
a = np.arange(20).reshape((5,4))
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [12, 13, 14, 15],
# [16, 17, 18, 19]])
# If I select certain rows, it works
print a[[0, 1, 3], :]
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [12, 13, 14, 15]])
# If I select certain rows and a single column, it works
print a[[0, 1, 3], 2]
# array([ 2, 6, 14])
# But if I select certain rows AND certain columns, it fails
print a[[0,1,3], [0,2]]
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# ValueError: shape mismatch: objects cannot be broadcast to a single shape
Why is this happening? Surely I should be able to select the 1st, 2nd, and 4th rows, and 1st and 3rd columns? The result I'm expecting is:
为什么会这样?当然,我应该能够选择1、2、4行、1、3列?我期待的结果是:
a[[0,1,3], [0,2]] => [[0, 2],
[4, 6],
[12, 14]]
3 个解决方案
#1
41
Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:
花哨的索引要求您提供每个维度的所有索引。您为第一个提供了3个索引,为第二个提供了2个索引,因此出现了错误。你想做这样的事情:
>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
That is of course a pain to write, so you can let broadcasting help you:
写这篇文章当然很痛苦,所以你可以让广播帮助你:
>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
This is much simpler to do if you index with arrays, not lists:
如果你用数组而不是列表来索引,这就简单多了:
>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
#2
30
As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.
正如Toan所建议的,一个简单的技巧是先选择行,然后再选择上面的列。
>>> a[[0,1,3], :] # Returns the rows you want
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]] # Selects the columns you want as well
array([[ 0, 2],
[ 4, 6],
[12, 14]])
[Edit] The built-in method: np.ix_
I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:
我最近发现numpy提供了一个内置的一行程序来执行@Jaime建议的操作,但是不需要使用广播语法(因为缺乏可读性)。从文档:
Using ix_ one can quickly construct index arrays that will index the cross product.
a[np.ix_([1,3],[2,5])]
returns the array[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]
.使用ix_one可以快速构建索引数组,从而索引跨产品。[np.ix_([1,3],[2、5]))返回的数组([[1,2][1,5]],[[3 2]一个[3,5]]]。
So you use it like this:
你可以这样使用它:
>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:
它的工作方式是按照Jaime建议的方式对数组进行对齐,这样广播才能正常进行:
>>> np.ix_([0,1,3], [0,2])
(array([[0],
[1],
[3]]), array([[0, 2]]))
Also, as MikeC says in a comment, np.ix_
has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:
另外,正如MikeC在评论中所说,np。ix_具有返回视图的优势,而我的第一个(预编辑)答案则没有。这意味着您现在可以分配给索引数组:
>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a
array([[-1, 1, -1, 3],
[-1, 5, -1, 7],
[ 8, 9, 10, 11],
[-1, 13, -1, 15],
[16, 17, 18, 19]])
#3
3
USE:
使用:
>>> a[[0,1,3]][:,[0,2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
OR:
或者:
>>> a[[0,1,3],::2]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
#1
41
Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:
花哨的索引要求您提供每个维度的所有索引。您为第一个提供了3个索引,为第二个提供了2个索引,因此出现了错误。你想做这样的事情:
>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
That is of course a pain to write, so you can let broadcasting help you:
写这篇文章当然很痛苦,所以你可以让广播帮助你:
>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
This is much simpler to do if you index with arrays, not lists:
如果你用数组而不是列表来索引,这就简单多了:
>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
#2
30
As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.
正如Toan所建议的,一个简单的技巧是先选择行,然后再选择上面的列。
>>> a[[0,1,3], :] # Returns the rows you want
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]] # Selects the columns you want as well
array([[ 0, 2],
[ 4, 6],
[12, 14]])
[Edit] The built-in method: np.ix_
I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:
我最近发现numpy提供了一个内置的一行程序来执行@Jaime建议的操作,但是不需要使用广播语法(因为缺乏可读性)。从文档:
Using ix_ one can quickly construct index arrays that will index the cross product.
a[np.ix_([1,3],[2,5])]
returns the array[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]
.使用ix_one可以快速构建索引数组,从而索引跨产品。[np.ix_([1,3],[2、5]))返回的数组([[1,2][1,5]],[[3 2]一个[3,5]]]。
So you use it like this:
你可以这样使用它:
>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:
它的工作方式是按照Jaime建议的方式对数组进行对齐,这样广播才能正常进行:
>>> np.ix_([0,1,3], [0,2])
(array([[0],
[1],
[3]]), array([[0, 2]]))
Also, as MikeC says in a comment, np.ix_
has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:
另外,正如MikeC在评论中所说,np。ix_具有返回视图的优势,而我的第一个(预编辑)答案则没有。这意味着您现在可以分配给索引数组:
>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a
array([[-1, 1, -1, 3],
[-1, 5, -1, 7],
[ 8, 9, 10, 11],
[-1, 13, -1, 15],
[16, 17, 18, 19]])
#3
3
USE:
使用:
>>> a[[0,1,3]][:,[0,2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
OR:
或者:
>>> a[[0,1,3],::2]
array([[ 0, 2],
[ 4, 6],
[12, 14]])