3

I have a 2D numpy array of 2D points:

np.random.seed(0)   
a = np.random.rand(3, 4, 2) # each value is a 2D point

I would like to sort each row by the norm of every point

norms = np.linalg.norm(a, axis=2) # shape(3, 4)

indices = np.argsort(norms, axis=0) # indices of each sorted row

Now I would like to create an array with the same shape and values as a. that will have each row of 2D points sorted by their norm.

How can I achieve that?

I tried variations of np.take & np.take_along_axis but with no success.

for example:

np.take(a, indices, axis=1) # shape (3,3,4,2)

This samples a 3 times, once for each row in indices. I would like to sample a just once. each row in indices has the columns that should be sampled from the corresponding row.

7
  • What variations did you try and how did they not succeed? Commented Oct 7, 2020 at 1:26
  • I'll be happy to nominate for reopening and post an answer when you fix the question Commented Oct 7, 2020 at 1:46
  • @MadPhysicist I edited the question with an example and a clarification. hopefully it is clear now. Commented Oct 7, 2020 at 1:49
  • @NinaKaprez Is the posted answer not what you are looking for? if not, could you please post a sample input and desired output? Commented Oct 7, 2020 at 1:49
  • What about take along axis? Also, shouldn't your argsort have axis=1? Or do you intend to sort columns rather than rows? Commented Oct 7, 2020 at 1:50

1 Answer 1

5

If I understand you correctly, you want this:

norms = np.linalg.norm(a,axis=2) # shape(3,4)
indices = np.argsort(norms , axis=1)
np.take_along_axis(a, indices[:,:,None], axis=1)

output for your example:

[[[0.4236548  0.64589411]
  [0.60276338 0.54488318]
  [0.5488135  0.71518937]
  [0.43758721 0.891773  ]]

 [[0.07103606 0.0871293 ]
  [0.79172504 0.52889492]
  [0.96366276 0.38344152]
  [0.56804456 0.92559664]]

 [[0.0202184  0.83261985]
  [0.46147936 0.78052918]
  [0.77815675 0.87001215]
  [0.97861834 0.79915856]]]
Sign up to request clarification or add additional context in comments.

5 Comments

no, the output should have the same shape as the variable 'a'.
@NinaKaprez It is the same shape. Is a not of shape (3,4,2)? If not, you would need to clarify better.
@Eshan, my bad. I think this is what I need. thanks! can you elaborate what indices[::None] does?
@NinaKaprez. It adds a new dimension at the None index. None is np.newaxis.
@NinaKaprez You are welcome. Could not have said better than Mad Physicist's comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.