How to sort multiple columns of a Pandas DataFrame?


To sort multiple columns of a Pandas DataFrame, we can use the sort_values() method.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame, df.

  • Initialize a variable col to sort the column.

  • Print the sorted DataFrame.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)
print "Input DataFrame is:
", df col = ["x", "y"] df = df.sort_values(col, ascending=[False, True]) print "After sorting column ", col, "DataFrame is:
", df

Output

Input DataFrame is:
   x  y  z
0  5  4  9
1  2  7  3
2  7  5  5
3  0  1  1

After sorting column ['x', 'y'] DataFrame is:
   x  y  z
2  7  5  5
0  5  4  9
1  2  7  3
3  0  1  1

Updated on: 30-Aug-2021

803 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements