Sorting a column in pandas python can be accomplished using sort_values() function. let’s see how to
- Sort column in pandas dataframe in ascending order (increasing order)
- Sort column in pandas dataframe in descending order (decreasing order)
First let’s create a dataframe
import pandas as pd import numpy as np df1 = { 'State':['Arizona','Georgia','Newyork','Indiana','Florida'], 'Score1':[4,47,55,74,31]} df1 = pd.DataFrame(df1,columns=['State','Score1']) print(df1)
df1 will be
Sort numeric column in pandas in ascending order
df1.sort_values('Score1',inplace=True) print (df1)
Sort_values() function sorts in ascending order. Inplace =True replaces the current column. So resultant dataframe will be
Sort numeric column in pandas in descending order:
df1.sort_values('Score1',inplace=True, ascending=False) print(df1)
Sort_values() function with ascending =False argument sorts in descending order. Inplace =True replaces the current column. So resultant dataframe will be
Sort character column in pandas – ascending order:
df1.sort_values('State',inplace=True) print (df1)
resultant dataframe will be
Sort character column in pandas in descending order:
df1.sort_values('State',inplace=True, ascending=False) print (df1)
resultant dataframe will be