【问题标题】:Python Pandas sorting by multiindex and columnPython Pandas 按多索引和列排序
【发布时间】:2016-01-16 09:30:36
【问题描述】:

在 Pandas 0.17 中,我尝试按特定列排序,同时保持分层索引(A 和 B)。 B 是通过连接设置数据帧时创建的流水号。我的数据如下所示:

          C      D
A   B
bar one   shiny  10
    two   dull   5
    three glossy 8
foo one   dull   3
    two   shiny  9
    three matt   12

这是我需要的:

          C      D
A   B
bar two   dull   5
    three glossy 8
    one   shiny  10
foo one   dull   3
    three matt   12
    two   shiny  9

下面是我正在使用的代码和结果。注意:Pandas 0.17 提醒 dataframe.sort 将被弃用。

df.sort_values(by="C", ascending=True)
          C      D
A   B
bar two   dull   5
foo one   dull   3
bar three glossy 8
foo three matt   12
bar one   shiny  10
foo two   shiny  9

添加 .groupby 会产生相同的结果:

df.sort_values(by="C", ascending=True).groupby(axis=0, level=0, as_index=True)

同样的,先切换到排序索引,再groupby列也没有什么成效:

df.sort_index(axis=0, level=0, as_index=True).groupby(C, as_index=True)

我不确定重新索引我需要保留第一个索引 A,第二个索引 B 可以重新分配,但不是必须的。如果没有简单的解决方案,我会感到惊讶;我想我只是找不到它。任何建议表示赞赏。


编辑:与此同时,我删除了第二个索引 B,将第一个索引 A 重新分配为一列,而不是对多列排序的索引,然后对其重新编制索引:

df.index = df.index.droplevel(1)
df.reset_index(level=0, inplace=True)
df_sorted = df.sort_values(["A", "C"], ascending=[1,1]) #A is a column here, not an index.
df_reindexed = df_sorted.set_index("A")

还是很冗长。

【问题讨论】:

    标签: python sorting pandas indexing


    【解决方案1】:

    感觉可能有更好的方法,但这里有一种方法:

    In [163]: def sorter(sub_df):
         ...:     sub_df = sub_df.sort_values('C')
         ...:     sub_df.index = sub_df.index.droplevel(0)
         ...:     return sub_df
    
    In [164]: df.groupby(level='A').apply(sorter)
    Out[164]: 
                    C   D
    A   B                
    bar two      dull   5
        three  glossy   8
        one     shiny  10
    foo one      dull   3
        three    matt  12
        two     shiny   9
    

    【讨论】:

    • 您的方法比我的中间解决方案更先进,但我同意应该有更好的方法。
    【解决方案2】:

    基于 chrisb 的代码:

    请注意,在我的例子中,它是一个 Series 而不是 DataFrame,

    s.groupby(level='A', group_keys=False).apply(lambda x: x.sort_values(ascending=False))
    

    【讨论】:

      猜你喜欢
      • 2015-04-06
      • 2018-05-02
      • 2019-08-16
      • 2021-01-07
      • 2016-10-22
      • 2017-08-29
      • 2017-04-10
      • 2020-04-30
      • 2018-08-29
      相关资源
      最近更新 更多