【发布时间】:2014-05-20 13:37:11
【问题描述】:
我一直想弄清楚我在这里做错了什么愚蠢的事情。
我正在使用 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]]
【问题讨论】:
-
标记numpy-slicing 以提高可查找性。 (此外,“切片”和“切片”这两个词不会出现在明文中,我们可以使用一些重复项,将这些词封闭在其中)
标签: python arrays numpy multidimensional-array numpy-slicing