首页 > 解决方案 > 为什么使用冒号与范围进行 numpy 索引会导致奇怪的行为?

问题描述

有人可以解释以下行为吗?

test = np.random.rand(1000, 10)
test.shape
(1000, 10)

idxs = np.random.randint(0, 10, 1000)
idxs.shape
(1000,)

test[:, idxs].shape
(1000, 1000)

test[range(test.shape[0]), idxs].shape
(1000,)

我希望这些是等效的。我错过了什么?

标签: pythonnumpy

解决方案


由于还没有人明确表示:您缺少参考手册的高级索引部分。

Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). 高级索引有两种类型:整数和布尔。

(我的粗体字)


推荐阅读