Search code examples
pythonpandasunit-testingsorting

Sort both columns and rows of a dataframe based on another dataframe


I have two dataframes with same values but different column order and index.

df1=
index   col1    col2    col3   col4
----------------------------------
0       1       2017    1.3   1
1       2       2017    2.4   1
2       3       2017    3.5   0
3       1       2018    3.5   0


df2=
index   col3    col1    col2    col4
------------------------------------
0       1       2018    3.5     0
1       3       2017    3.5     0
2       1       2017    1.3     1
3       2       2017    2.4     1

Is there a way to transform one so that one becomes identical to the other?

I have found a way to sort columns

df1 = df1[df2.columns]

but I don't find a way to reorder rows.


Solution

  • Does this work?

    df1.sort_values(by='col3') # change to the column you want to sort the rows by
    

    You can use a list to sort by multiple columns

    df1.sort_values(by=df2.columns)
    df1.sort_values(by=['col3', 'col4'])
    

    By default, sort_values sorts in ascending order. If you want the rows to be sorted in descending order you can use something like this:

    df1.sort_values(by=['col3', 'col4'], ascending=False)