Error when indexing with 2 dimensions in NumPy

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?

Best answer


operates in 2 steps, first selecting 2 columns, and then 3 rows from that result


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


np.ix_ can help generate these index arrays.

In [140]: np.ix_([0,3,4],[91,1063])
        [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:

I’m basically repeating my answer to Composite Index updates for Numpy Matrices