我一直在疯狂地想弄明白我在这里做错了什么蠢事。
我使用的是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]]
使用:
或:
奇特的索引要求您为每个维度提供所有索引。您为第一个索引提供了3个索引,而第二个索引仅提供了2个索引,因此出现了错误。你想这样做:
这当然是一个痛苦的写作,所以你可以让广播帮助你:
如果使用数组而不是列表编制索引,则此操作要简单得多:
正如Toan所建议的,一个简单的技巧就是先选择行,然后选择上的列。
[编辑]内置方法:^{}
我最近发现,numpy为您提供了一个内置的一行程序,让您完全按照@Jaime的建议执行操作,但不必使用广播语法(这是因为缺乏可读性)。从文档中:
所以你这样使用它:
它的工作方式是按照Jaime的建议调整阵列,这样广播就可以正常进行:
而且,正如MikeC在评论中所说,
np.ix_
具有返回视图的优势,而我的第一个(预编辑)答案没有返回视图。这意味着您现在可以将分配给索引数组:相关问题 更多 >
编程相关推荐