Numpy Gear Cut

I have an operation that I usually do, which I call a “jagged cut” because I don’t know the real name. This is best explained with an example:

a = np.random.randn(50, 10)
entries_of_interest = np.random.randint(10, size = 50)  # Vector of 50 indices between 0 and 9
# Now I want the values contained in each row of a at the corresponding index in "entries of interest"
jagged_slice_of_a = a[np.arange(a.shape[0]), entries_of_interest]
# jagged_slice_of_a is now a vector with 50 elements.  Good.

The only problem is it’s a little cumbersome to do for indexing a[np.arange(a.shape[0]), entries_of_interest](it seems silly to build "np.arange (a.shape [0])" just for that). I would like something like an operator :for this, but :do something else. Is there a shorter way to do this operation?

The best answer:

No, there is no better way with native numpy. You can create a helper function for this if you want.

+4
source share
3 answers

I think your current method is probably the best way.

You can also use choosefor such a choice. This is syntactically clearer, but harder to get right and potentially more limited. The equivalent of this method would be:

entries_of_interest.choose(a.T)
+3
source

Elements in jagged_slice_of_aare diagonal elements.a[:,entries_of_interest]

A slightly less cumbersome way to do this would therefore be np.diagonalto use to extract them.

jagged_slice_of_a = a[:, entries_of_interest].diagonal()
+1
source

, , .

a[np.arange(a.shape[0]), entries_of_interest]

, , a[:, entries_of_interest] numpy. - , () .

-

a[I, J]

I J - 2 . entries_of_interest a.shape[0] ( ) ( ) 2d. .

SO, , a.flat. I*n+J .

J, I , numpy . , - ,

def  peter_selection(a,I):
   # check the a.shape[0]==I.shape[0]
   return a[np.arange(a.shape[0]), I]
+1

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


All Articles