How to sort a column of a Pandas DataFrame?


To sort a column in a Pandas DataFrame, we can use the sort_values() method.

Steps

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

  • Print 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, 10, 5, 1],
    `"z": [9, 3, 5, 1]
  }
)

print "Input DataFrame is:
", df col = "x" df = df[col].sort_values(ascending=False) print "After sorting column ", col, "DataFrame is:
", df

Output

Input DataFrame is:
   x  y  z
0  5  4  9
1  2 10  3
2  7  5  5
3  0  1  1
After sorting column x DataFrame is:
2  7
0  5
1  2
3  0
Name: x, dtype: int64

Updated on: 30-Aug-2021

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements