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
JavaScript
x
3
1
out = (df.apply(lambda row: sorted(row), axis=1, result_type='expand')
2
.set_axis(df.columns, axis=1))
3
JavaScript
1
7
1
print(out)
2
3
Col1 Col2
4
0 Anna Bonnie
5
1 Connor Ethan
6
2 Daniel Sophia
7