2

consider the array a

np.random.seed([3,1415])
a = np.random.choice(np.arange(8), (2, 4), False)
print(a)

[[7 1 4 5]
 [6 2 3 0]]

I'll create another array b that holds the results of np.argsort along each row.

b = a.argsort(1)
print(b)

[[1 2 3 0]
 [3 1 2 0]]

I want to produce the sorted version of a by doing an appropriate slice of a with b. It should look like this

idx0 = np.arange(a.shape[0]).repeat(a.shape[1])
print(a[idx0, b.ravel()].reshape(a.shape))

[[1 4 5 7]
 [0 2 3 6]]

question
what is the appropriate way to slice an 2 x 4 array with another 2 x 4 array in the fashion described above?

0

1 Answer 1

2

Advanced-indexing for the help -

a[np.arange(b.shape[0])[:,None],b]

Sample run -

In [10]: a
Out[10]: 
array([[7, 1, 4, 5],
       [6, 2, 3, 0]])

In [11]: b
Out[11]: 
array([[1, 2, 3, 0],
       [3, 1, 2, 0]])

In [12]: a[np.arange(b.shape[0])[:,None],b]
Out[12]: 
array([[1, 4, 5, 7],
       [0, 2, 3, 6]])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.