简体   繁体   中英

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 ?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM