我已经疯了,想弄清楚我在这里做了什么蠢事。
我使用的是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为什么会发生这种情况?当然,我应该能够选择第一、第二、第四行、第一和第三列?我期待的结果是:
a[[0,1,3], [0,2]] => [[0, 2],
[4, 6],
[12, 14]]发布于 2014-04-08 04:59:26
高级索引要求您为每个维度提供所有索引。您为第一个索引提供了3个索引,对于第二个索引只提供了2个索引,因此出现了错误。你想做这样的事
>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])这当然是一个痛苦的写作,所以你可以让广播帮助你:
>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])如果使用数组(而不是列表)进行索引,这要简单得多:
>>> 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]])发布于 2014-04-08 08:10:36
正如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]])编辑内置方法:np.ix_
我最近发现,numpy为您提供了一个内置的一行程序来执行@Jaime建议的操作,但不需要使用广播语法(因为缺乏可读性)。从医生那里:
使用ix_可以快速构造索引数组,从而对交叉产品进行索引。
a[np.ix_([1,3],[2,5])]返回数组[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]。
所以你就这样用它:
>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0, 2],
[ 4, 6],
[12, 14]])它的工作方式是按照Jaime建议的方式对齐阵列,这样广播就能正常地进行:
>>> np.ix_([0,1,3], [0,2])
(array([[0],
[1],
[3]]), array([[0, 2]]))此外,正如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]])发布于 2014-04-08 07:39:43
使用:
>>> a[[0,1,3]][:,[0,2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])或:
>>> a[[0,1,3],::2]
array([[ 0, 2],
[ 4, 6],
[12, 14]])https://stackoverflow.com/questions/22927181
复制相似问题