0

How can I sort a data frame based on column which is again dependent on other column ?

DF :

A   B   C
ww  a   70
ww  b   90
ww  c   100
qq  a   100
qq  b   80
qq  c   90
rr  a   80
rr  b   70
rr  c   100

I want the column C to sorted with respective to column A. That means my column A should be ascending, within the column C the values should change in ascending without out chnage in the order of column A.

Output:

A   B   C
qq  b   80
qq  c   90
qq  a   100
rr  b   70
rr  a   80
rr  c   100
ww  a   70
ww  b   90
ww  c   100

Column A is sorted and column C is also sorted.

learner
  • 7
  • 1

1 Answers1

1

Just use df.sort_values(['A', 'C'], ascending=[1, 1]) to sort first by A then by C both in ascending order:

import pandas as pd

d = {'A': ['ww','ww','ww', 'qq', 'qq', 'qq', 'rr', 'rr', 'rr'],
     'B': ['a','b','c','a','b','c','a','b','c'],
     'C': [70, 90, 100, 100, 80, 90, 80, 70, 100]}
df = pd.DataFrame(d)
df = df.sort_values(['A', 'C'], ascending=[1, 1])
print(df)

Output

    A  B    C
4  qq  b   80
5  qq  c   90
3  qq  a  100
7  rr  b   70
6  rr  a   80
8  rr  c  100
0  ww  a   70
1  ww  b   90
2  ww  c  100
b-fg
  • 3,959
  • 2
  • 28
  • 44