pandas Sort one or more columns of of by their values

  • 2021-08-21 20:53:17
  • OfStack

Sort by a 1 column


d = {'A': [3, 6, 6, 7, 9], 'B': [2, 5, 8, 0, 0]}
df = pd.DataFrame(data=d)
print(' Before sorting :\n', df)
'''
 Before sorting :
 A B
0 3 2
1 6 5
2 6 8
3 7 0
4 9 0
'''
res = df.sort_values(by='A', ascending=False)
print(' According to A Sorting the values of columns :\n', res)
'''
 According to A Sorting the values of columns :
 A B
4 9 0
3 7 0
1 6 5
2 6 8
0 3 2
'''

Sort by multiple columns


d = {'A': [3, 6, 6, 7, 9], 'B': [2, 5, 8, 0, 0]}
df = pd.DataFrame(data=d)
print(' Before sorting :\n', df)
'''
 Before sorting :
 A B
0 3 2
1 6 5
2 6 8
3 7 0
4 9 0
'''
res = df.sort_values(by=['A', 'B'], ascending=[False, False])
print(' According to A Column B Sorting the values of columns :\n', res)
'''
 According to A Column B Sorting the values of columns :
 A B
4 9 0
3 7 0
2 6 8
1 6 5
0 3 2
'''

Related articles: