In this article we will discuss how to sort a 2D Numpy array by single or multiple rows or columns.

Sorting 2D Numpy Array by a column

First of all import numpy module i.e.

Now suppose we have a 2D Numpy array i.e.

Output:

Now suppose we want to sort this 2D numpy array by 2nd column like this,

For this we need to change positioning of all rows in 2D numpy array based on sorted values of 2nd column i.e. column at index 1. Let’s see how to do that,

Sorting 2D Numpy Array by column at index 1

Output:

It sorted the 2D Numpy array by 2nd column i.e. column at index 1.

How did it worked ?
Let’s break down the above expression part by part and understand how ot worked.

Select the column at index 1 from 2D numpy array i.e.

It returns the values at 2nd column i.e. column at index position 1 i.e.

Now get the array of indices that sort this column i.e.

It returns the index positions that can sort the above column i.e.

It means for sorting column at index position 1 use following order of rows : [1 2 0]
So, to change the positioning of rows based on values returned by argsort(). Pass that to [] operator of 2D numpy array i.e.

It will change the row order and make the 2D numpy array sorted by 2nd column i.e. by column at index position 1.

Let’s see some other examples,

Sorting 2D Numpy Array by column at index 0

Output:

Sorting 2D Numpy Array by last column

Output:

Sort a 2D Numpy Array by row

On the similar logic we can sort a 2D Numpy array by a single row i.e. shuffle the columns of 2D numpy array to make the given row sorted.

Let’s understand by examples,

Suppose we have a 2D Numpy array i.e.

Output:

Sorting 2D Numpy Array by row at index position 1

Let’s sort the above created 2D Numpy array by 2nd row i.e. row at index position 1 i.e.

Output:

It changed the positions of all columns in 2D numpy array to make row at index position 1 sorted. So, basically we sorted the 2D Numpy array by row at index 1.

How it worked ?

Its logic was similar to above i.e. Select row at given index position using [] operator and then get sorted indices of this row using argsort().

Then change the positioning of columns to make this 2d array sorted by row.

Some other examples,

Sorting 2D Numpy Array by First Row

Output:

Sorting 2D Numpy Array by Last row

Output:

Complete example is as follows:

Output:

Click Here to Subscribe for more Articles / Tutorials like this.