How to use NumPy to sort by column in an array?

This recipe explains how to use NumPy to sort by column in an array in Python.

Efficiently organizing and manipulating data is a fundamental aspect of data science and numerical computing. NumPy, a Python ibrary, offers a variety of tools to work with arrays and matrices. In this guide, we will delve into the world of sorting NumPy arrays by columns, a crucial skill for various data analysis and manipulation tasks. Whether you need to sort by the first column, second column, or any other column, NumPy provides a straightforward method for achieving this. Let's explore how to use NumPy to sort by a specific column efficiently.

Learn how to build Regression (Linear,Ridge,Lasso) Models in NumPy Python 

How to sort NumPy Array by column in Python?

Learn how to sort a numpy array by a column with these easy-to-follow steps

Step 1: Importing the NumPy library

Begin by importing the NumPy library into your Python environment. NumPy is a versatile library that is instrumental in data manipulation and enables a range of mathematical operations.

import numpy as np

This import is the starting point for utilizing NumPy's array sorting functions effectively.

Step 2: Define a Random NumPy Array

Before we teach your how to sort an array by column using numpy, you need to create a random NumPy array with multiple rows and columns. For this example, we've defined a sample 2D array to demonstrate the sorting process.

a = np.array([[9, 2, 3],[4, 5, 6],[7, 0, 5]])

This 'a' array serves as our data to be sorted by one of its columns.

Step 3: Use NumPy to sort 2D array by Second column

To sort the NumPy array by a particular column, use NumPy's argsort() function. In this example, we're sorting the array by the second column (index 1). The sorted array will be stored in 'a'.

a = a[a[:,1].argsort()] 

print(a)

This code efficiently sorts 'a' by its second column. You can adapt this code to sort by any other column of interest. For example, if you want to learn how to sort a NumPy 2D array by first  column, use ‘0’ index instead of ‘1’ index.

Scroll down to the ipython file below to visualize the output.

Dive into NumPy with ProjectPro!

The ability to sort NumPy arrays by columns is a valuable skill that finds application in various data science problems. NumPy's straightforward sorting methods streamline the process and enhance your data manipulation capabilities. Whether you are working with large datasets, conducting statistical analyses, or organizing information for further research, NumPy's sorting functionality can significantly improve your workflow.

To further refine your data science skills and gain practical experience, explore  ProjectPro. It's a platform that offers over 250 solved projects in data science and big data, allowing you to apply your knowledge in real-world situations and advance your career. Begin your journey of skill development today.

What Users are saying..

profile image

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.

Learn to Build a Polynomial Regression Model from Scratch
In this Machine Learning Regression project, you will learn to build a polynomial regression model to predict points scored by the sports team.

Demand prediction of driver availability using multistep time series analysis
In this supervised learning machine learning project, you will predict the availability of a driver in a specific area by using multi step time series analysis.

LLM Project to Build and Fine Tune a Large Language Model
In this LLM project for beginners, you will learn to build a knowledge-grounded chatbot using LLM's and learn how to fine tune it.

Build Classification Algorithms for Digital Transformation[Banking]
Implement a machine learning approach using various classification techniques in Python to examine the digitalisation process of bank customers.

Linear Regression Model Project in Python for Beginners Part 2
Machine Learning Linear Regression Project for Beginners in Python to Build a Multiple Linear Regression Model on Soccer Player Dataset.

Build an End-to-End AWS SageMaker Classification Model
MLOps on AWS SageMaker -Learn to Build an End-to-End Classification Model on SageMaker to predict a patient’s cause of death.

Predictive Analytics Project for Working Capital Optimization
In this Predictive Analytics Project, you will build a model to accurately forecast the timing of customer and supplier payments for optimizing working capital.

Deploy Transformer-BART Model on Paperspace Cloud
In this MLOps Project you will learn how to deploy a Tranaformer BART Model for Abstractive Text Summarization on Paperspace Private Cloud

End-to-End ML Model Monitoring using Airflow and Docker
In this MLOps Project, you will learn to build an end to end pipeline to monitor any changes in the predictive power of model or degradation of data.