【问题标题】:Sort aggregated column in multiindex dataframe within groups对组内多索引数据框中的聚合列进行排序
【发布时间】:2021-01-30 22:55:54
【问题描述】:

here 的数据中汲取灵感,我们有以下系列/数据框

df = data.groupby(["Manufacturer","Product Name","Product Launch Data"]).sum("total")

                                                 total
Manufacturer Product Name Product Launch Date       
Apple        iPad         2010-04-03              30
             iPod         2001-10-23              34
Samsung      Galaxy       2009-04-27              24
             Galaxy Tab   2010-09-02              22

我们如何在total 之后排序,同时仍然保留组,即以:

                                                 total
Manufacturer Product Name Product Launch Date       
Apple        iPad         2010-04-03              30
             iPod         2001-10-23              34
Samsung      Galaxy Tab   2010-09-02              22
             Galaxy       2009-04-27              24

【问题讨论】:

    标签: python pandas multi-index


    【解决方案1】:

    在最后的熊猫版本中,可以按级别和列名一起排序,所以在这里工作:

    df = df.sort_values(['Manufacturer','total'])
    print (df)
                                                   total
    Manufacturer Product Name Product Launch Date       
    Apple        iPad         2010-04-03              30
                 iPod         2001-10-23              34
    Samsung      Galaxy Tab   2010-09-02              22
                 Galaxy       2009-04-27              24
    

    【讨论】:

    • 谢谢!我怎么没看到——我一直盯着文档这么久了
    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 2018-12-01
    • 2018-10-09
    • 2017-12-26
    • 2017-01-12
    • 2020-07-10
    • 1970-01-01
    • 2016-01-04
    相关资源
    最近更新 更多