Skip to content
Advertisement

How to using numpy.argsort on a 2D array to sort another 2D array

I use numpy.argsort all the time for 1D data, but it seems to behaving differently in 2D.

For example, let’s say I want to argsort this array along axis 1 so the items in each row are in ascending order

JavaScript

All fine so far.

Each row in the above gives the order to how the columns should be rearranged in the second array.

Let’s say we want to sort the array below with the above idx.

JavaScript

The shape now has an added dimensions.

I was expecting to get.

JavaScript

I can do this iterating over the rows, which is bad!

JavaScript

Advertisement

Answer

np.take_along_axis has an example using argsort:

JavaScript

This streamlines a process of applying ai to the array itself. We can do that directly, but it requires a bit more thought about what the index actually represents.

In this example, ai are index values along axis 1 (values like 0,1,or 2). This (2,3) has to broadcast with a (2,1) array for axis 0:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement