Search code examples
pythonpandasdataframesortinggroup-by

How to sort a dataframe by its values horizontally


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

Solution

    1. sort the values of the dataframe ascendingly

      df.values.sort()

    2. reverse its order

      df[df.columns][::-1]