我一直想弄清楚我在这里做错了什么愚蠢的事情。
我正在使用 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]]
最佳答案
正如 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 的建议进行操作,但不必使用广播语法(由于缺乏可读性)。来自文档:
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]]]
.
所以你可以这样使用它:
>>> 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_
具有返回 View 的优势,而我的第一个(预编辑)答案没有。这意味着您现在可以分配到索引数组:
>>> 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]])
关于python - 从 NumPy 数组中选择特定的行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22927181/