【发布时间】:2012-04-01 01:08:12
【问题描述】:
我可以用一个元组甚至一个元组列表来索引一个二维 numpy 数组
a = numpy.array([[1,2],[3,4]])
i = [(0,1),(1,0)] # edit: bad example, should have taken [(0,1),(0,1)]
print a[i[0]], a[i]
(给2 [2 3])
但是,我不能用向量算术来操作元组,即
k = i[0]+i[1]
没有给出想要的(1,1),而是连接起来。
另一方面,使用 numpy 数组作为索引,算术有效,但索引不起作用。
i = numpy.array(i)
k = i[0]+i[1] # ok
print a[k]
给出数组[[3 4], [3 4]],而不是所需的4。
有没有办法对索引进行矢量算术运算,但也可以索引 numpy 数组 与他们一起(不从元组派生类并重载所有运算符)?
This question 起初看起来很有希望,但我不知道是否可以将其应用于我的情况。
编辑(对接受的答案发表评论):
...然后使用 map 处理索引数组也可以正常工作
arr = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
ids = numpy.array([(0,1),(1,0)])
ids += (0,1) # shift all indices by 1 column
print arr[map(tuple,ids.T)]
(不过,这让我很困惑为什么我需要转置。 上面也会遇到这个问题, 并且很幸运有 [(0,1),(0,1)])
【问题讨论】:
标签: python numpy indexing multidimensional-array