Reputation: 7476
Why does this work:
>>> (tf[:,[91,1063]])[[0,3,4],:]
array([[ 0.04480133, 0.01079433],
[ 0.11145042, 0. ],
[ 0.01177578, 0.01418614]])
But this does not:
>>> tf[[0,3,4],[91,1063]]
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,)
What am I doing wrong?
Upvotes: 9
Views: 6994
Reputation: 231385
tf[:,[91,1063]])[[0,3,4],:]
operates in 2 steps, first selecting 2 columns, and then 3 rows from that result
tf[[0,3,4],[91,1063]]
tries to select tf[0,91]
, tf[3,1063]
and ft[4, oops]
.
tf[[[0],[3],[4]], [91,1063]]
should work, giving the same result as your first expression. think of the 1st list being a column, selecting rows.
tf[np.array([0,3,4])[:,newaxis], [91,1063]]
is another way of generating that column index array
tf[np.ix_([0,3,4],[91,1063])]
np.ix_
can help generate these index arrays.
In [140]: np.ix_([0,3,4],[91,1063])
Out[140]:
(array([[0],
[3],
[4]]), array([[ 91, 1063]]))
These column and row arrays are broadcast together to produce a 2d array of coordinates
[[(0,91), (0,1063)]
[(3,91), ... ]
.... ]]
This is the relevant part of the docs: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#purely-integer-array-indexing
I'm basically repeating my answer to Composite Index updates for Numpy Matrices
Upvotes: 10