【问题标题】:Sort a Dataframe with a coumn from another Dataframe使用来自另一个 Dataframe 的列对 Dataframe 进行排序
【发布时间】:2019-11-28 10:36:12
【问题描述】:

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

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

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    首先将Order列添加到df2:

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

    然后进行排序并删除 Order 列:

    df2.sort_values('Order').drop('Order', 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-31
      • 2022-12-11
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多