sort a dataframe in python pandas – By single & multiple column

How to sort a dataframe in python pandas by ascending order and by descending order on multiple columns with an example for each . our focus on this exercise will be on

  • how to sort a pandas dataframe in python by Ascending and Descending
  • how to sort a python pandas dataframe by single column
  • how to sort a pandas dataframe by multiple columns.

Let’s try with an example:

Create a dataframe:

import pandas as pd
import numpy as np

#Create a Dictionary of series
d = {'Name':pd.Series(['Alisa','Bobby','Cathrine','Madonna','Rocky','Sebastian','Jaqluine',
   'Rahul','David','Andrew','Ajay','Teresa']),
   'Age':pd.Series([26,27,25,24,31,27,25,33,42,32,51,47]),
   'Score':pd.Series([89,87,67,55,47,72,76,79,44,92,99,69])}

#Create a DataFrame
df = pd.DataFrame(d)
print df

the resultant dataframe will be

Sorting pandas dataframe in Python – By single & multiple column 1

 

Sort the python pandas Dataframe by single column – Ascending order:

The following code sorts the pandas dataframe by ascending values of the column Score

# sort the pandas dataframe by ascending value of single column

df.sort_values(by='Score')

sorting-pandas-dataframe-in-python-by-single-multiple-column-2

Sort a Dataframe in python pandas by single Column – descending order

The following code sorts the pandas dataframe by descending values of the column Score

# sort the pandas dataframe by descending value of single column

df.sort_values(by='Score',ascending=0)

sorting-pandas-dataframe-in-python-by-single-multiple-column-3

 

Sort the pandas Dataframe by Multiple Columns

 In the following code, we will sort the pandas dataframe by multiple columns (Age, Score).

We will first sort with Age by ascending order and then with Score by descending order

# sort the pandas dataframe by multiple columns

df.sort_values(by=['Age', 'Score'],ascending=[True,False])

Sorting-pandas-dataframe-in-Python-–-By-single-multiple column

Also refer sort a pandas dataframe by index

Sorting pandas dataframe in Python – By single & multiple column previous                                                                                                           next Sorting pandas dataframe in Python – By single & multiple column

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.