Kallol
Kallol

Reputation: 2189

Sort a column based on the sorting of a column from another pandas data frame

I have a dataframe like this:

 df1:
 col1    col2 
  P        1
  Q        3
  M        2

I have another dataframe:

df2:
col1      col2
 Q         1
 M         3
 P         9

I want to sort the col1 of df2 based on the order of col1 of df1. So the final dataframe will look like:

 df3:
 col1     col2
  P         1
  Q         3
  M         9

How to do it using pandas or any other effective method ?

Upvotes: 1

Views: 122

Answers (1)

yatu
yatu

Reputation: 88236

You could set col1 as index in df2 using set_index and index the dataframe using df1.col11 with .loc:

df2.set_index('col1').loc[df1.col1].reset_index()

   col1  col2
0    P     9
1    Q     1
2    M     3

Or as @jpp suggests you can also use .reindex instead of .loc:

df2.set_index('col1').reindex(df1.col1).reset_index()

Upvotes: 3

Related Questions