Skip to content
Advertisement

pandas sort alphabetically for every row based on column content

I have a dataframe that looks like this:

Col1 Col2
Bonnie Anna
Connor Ethan
Sophia Daniel

And I want to sort its content alphabetically so that the final result is:

Col1 Col2
Anna Bonnie
Connor Ethan
Daniel Sophia

I want each pair to be ordered alphabetically. As they are in different columns, I don’t know how to sort them directly with sort_values method. Thanks!

Advertisement

Answer

You can sort each row with DataFrame.apply

out = (df.apply(lambda row: sorted(row), axis=1, result_type='expand')
       .set_axis(df.columns, axis=1))
print(out)

     Col1    Col2
0    Anna  Bonnie
1  Connor   Ethan
2  Daniel  Sophia
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement