最佳答案
我一直在想我到底做错了什么。
我正在使用 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]]