用另一个数据框的列对一个数据框进行排序

时间:2019-07-19 12:17:20

标签: python-3.x pandas dataframe

我有两个看起来像这样的数据框。

df1 = 

Name    Order

John    2
Alice   3
Alisha  1
Mike    5
Katie   6
Steve   4


df2 = 

Name   Condition    Action

Mike    Stable      Out
Mike    Unstable    In
Steve   Stable      Out
Steve   Unstable    In
Katie   Stable      Out
Katie   Unstable    In
Alisha  Stable      Out
Alisha  Unstable    In
John    Stable      Out
John    Unstable    In
Alice   Stable      Out
Alice   Unstable    In

我想根据df1中提供的订单号对df2进行排序。

我尝试使用.index()和.reindex(),但是由于df2中有重复的行,因此出现错误。 ValueError:无法从重复的轴重新索引

预期结果应该是这样的。

df_sort = 

Name    Condition    Action

Alisha  Stable       Out
Alisha  Unstable     In
John    Stable       Out
John    Unstable     In
Alice   Stable       Out
Alice   Unstable     In
Steve   Stable       Out
Steve   Unstable     In
Mike    Stable       Out
Mike    Unstable     In
Katie   Stable       Out
Katie   Unstable     In

1 个答案:

答案 0 :(得分:1)

首先将Order列添加到df2:

df2['Order'] = df2.Name.map(df1.set_index('Name').Order)

然后进行排序并删除“订单”列:

df2.sort_values('Order').drop('Order', 1)
相关问题