sort 2d numpy array by values in a given column

Sort a Numpy Array by a Specific Column

In this tutorial, we will look at how to sort a numpy array by a column with the help of some examples.

To sort a numpy array by a given column, use the following steps –

  1. Get the column index, i. For example, if you want to sort the array by values in the second column, i will be 1 (rows and columns and indexed starting from 0).
  2. Get the index array of the rows after sorting by the above column using the argsort() method.
  3. Use the above index array to reorder the rows.

The following is the syntax –

# sort 2d numpy array by the column with index i
sorted_arr = arr[arr[:, i].argsort()]

The above code sorts the array by the values in the column with the index i in ascending order. To sort in descending order, reverse the values resulting from the argsort() function.

sort 2d numpy array by values in a given column

Let’s now look at some examples of using the above syntax –

Example 1 – Sort 2d array by a column in ascending order

import numpy as np

# create a numpy array
arr = np.array([
    [1, 7, 1],
    [2, 5, 0],
    [3, 9, 0]
])

# sort the above array by the second column, i=1
sorted_arr = sorted_arr = arr[arr[:, 1].argsort()]
print(sorted_arr)

Output:

[[2 5 0]
 [1 7 1]
 [3 9 0]]

You can see that the resulting array is sorted by the second column in ascending order.

Example 2 – Sort 2d array by a column in descending order

We can similarly sort a 2d array (by a specific column) in descending order. To do this, reverse the row indices obtained from the argsort() method. This will give the array of row indices when sorted in descending order.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Let’s take the same example as above.

import numpy as np

# create a numpy array
arr = np.array([
    [1, 7, 1],
    [2, 5, 0],
    [3, 9, 0]
])

# sort the above array in descending order by the second column, i=1
sorted_arr = sorted_arr = arr[arr[:, 1].argsort()[::-1]]
print(sorted_arr)

Output:

[[3 9 0]
 [1 7 1]
 [2 5 0]]

The resulting array is sorted in descending order by the second column.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top