我已经疯了,想弄清楚我在这里做了什么蠢事。
我使用的是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]]发布于 2020-01-25 21:24:29
使用np.ix_是最方便的方法(正如其他人所回答的),但也可以这样做:
>>> rows = [0, 1, 3]
>>> cols = [0, 2]
>>> (a[rows].T)[cols].T
array([[ 0, 2],
[ 4, 6],
[12, 14]])https://stackoverflow.com/questions/22927181
复制相似问题