How to sort a dataframe by its values horizontally
Question:
Say you have the following dataframe:
Columns X Y Z
Index_Col
A 1.0 3.0 2.0
B 1.0 3.0 2.0
C 1.0 3.0 2.0
How do you sort the values horizontally so that it becomes:
Columns Y Z X
Index_Col
A 3.0 2.0 1.0
B 3.0 2.0 1.0
C 3.0 2.0 1.0
Answers:
-
sort the values
of the dataframe ascendingly
df.values.sort()
-
reverse its order
df[df.columns][::-1]
Heres the answer cuz i also was having same problem:
df.sort_values(by = 'row_name', axis = 1)
https://www.geeksforgeeks.org/sort-rows-or-columns-in-pandas-dataframe-based-on-values/
Say you have the following dataframe:
Columns X Y Z
Index_Col
A 1.0 3.0 2.0
B 1.0 3.0 2.0
C 1.0 3.0 2.0
How do you sort the values horizontally so that it becomes:
Columns Y Z X
Index_Col
A 3.0 2.0 1.0
B 3.0 2.0 1.0
C 3.0 2.0 1.0
-
sort the
values
of the dataframe ascendinglydf.values.sort()
-
reverse its order
df[df.columns][::-1]
Heres the answer cuz i also was having same problem:
df.sort_values(by = 'row_name', axis = 1)
https://www.geeksforgeeks.org/sort-rows-or-columns-in-pandas-dataframe-based-on-values/