Error when indexing with 2 dimensions in NumPy

Why does it work:

>>> (tf[:,[91,1063]])[[0,3,4],:] array([[ 0.04480133, 0.01079433], [ 0.11145042, 0. ], [ 0.01177578, 0.01418614]]) 

But this is not so:

 >>> 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?

+6
source share
1 answer
 tf[:,[91,1063]])[[0,3,4],:] 

works in 2 stages, first selects 2 columns and then 3 rows from this result

 tf[[0,3,4],[91,1063]] 

trying 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 that the first list is a column, selecting rows.

 tf[np.array([0,3,4])[:,newaxis], [91,1063]] 

is another way to generate this array of column indices

 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 passed together to create a 2d array of coordinates

 [[(0,91), (0,1063)] [(3,91), ... ] .... ]] 

This is an important part of the docs: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#purely-integer-array-indexing

I basically reiterate my answer to Numpy's Composite Index Updates

+9
source

Source: https://habr.com/ru/post/986993/


All Articles