I can index a 2d numpy array with a tuple or even a list of tuples
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]
(Gives 2 [2 3]
)
However, I can not manipulate the tuples with vector arithmetic, i.e.
k = i[0]+i[1]
does not give the desired (1,1)
but concatenates.
On the other hand using numpy arrays for the indices, the arithmetic works, but the indexing does not work.
i = numpy.array(i)
k = i[0]+i[1] # ok
print a[k]
gives the array [[3 4], [3 4]]
instead of the desired 4
.
Is there a way to do vector arithmetic on the indices but also be able to index a numpy array with them (without deriving a class from tuple and overloading all the operators)?
This question looked promising at first but I could not figure out if I can apply it to my situation.
Edit (comment on accepted answer):
... and working on arrays of indices then works as well using 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)]
(confusing to me why I need the transpose, though. Would have run into this problem above as well, and was just fortunate with [(0,1),(0,1)])