Home > other >  Sort two groups of columns in dataframe separately?
Sort two groups of columns in dataframe separately?

Time:05-11

a = pd.DataFrame({'Foo':['A_1', 'A_4', 'A_3','A_6'],'Doo':['5', '7', '6','9'], 'Goo':[True, False, False, True]})

b = pd.DataFrame({'Poo':['A_6', 'A_1', 'A_3','A_4'], 'Moo':['1', '2', '3','4'],'Roo':[False, True, True, True]})

result=pd.concat([a, b], axis=1).sort_values('Poo')

is it possible to sort by two values or would I need to split the dataframe here? this is the desired output:

Foo Doo   Goo Poo Moo   Roo
A_1   5  True A_1   2  True
A_3   6 False A_3   3  True
A_4   7 False A_4   4  True
A_6   9  True A_6   1 False

CodePudding user response:

You can use merge instead of concat, so that the values of the columns Foo and Poo match. Then you can sort according to Foo (or Poo, same thing).

result = pd.merge(left=a, right=b,
                  left_on='Foo', right_on='Poo').sort_values('Foo')
  • Related