【问题标题】:How to create a multiindex dataframe that is sorted according to group size?如何创建根据组大小排序的多索引数据框?
【发布时间】:2020-03-06 02:38:59
【问题描述】:

我确实有这样的数据框:

df = pd.DataFrame({
    'IDs': list('abcdefgh'),
    'Val': [
        'foo', 'bar', 'foo', 'abc', 'bar', 'bar', 'foo', 'foo'
    ]
})

  IDs  Val
0   a  foo
1   b  bar
2   c  foo
3   d  abc
4   e  bar
5   f  bar
6   g  foo
7   h  foo

我现在想得到这样的输出:

Val IDs           
foo a            
    c            
    g            
    h            
bar b            
    e            
    f            
abc d

因此,它是根据Val 中每个组的size 排序的多索引数据帧的索引。

我目前是这样做的:

df['groupsize'] = df.groupby('Val')['IDs'].transform('size')

df = (
    df.sort_values(['groupsize', 'Val', 'IDs'], ascending=[False, True, True])
      .drop('groupsize', axis=1)
      .set_index(['Val', 'IDs'])
)

df.to_excel('example.xlsx', merge_cells=True)

它给出了所需的输出。

有没有办法实现相同的输出但不创建这个中间列 groupsize 无论如何都会被删除?

【问题讨论】:

    标签: python pandas sorting dataframe multi-index


    【解决方案1】:

    使用set_indexvalue_counts

    df.set_index('Val').loc[df.Val.value_counts().index]
    
    Out[44]:
        IDs
    Val
    foo   a
    foo   c
    foo   g
    foo   h
    bar   b
    bar   e
    bar   f
    abc   d
    

    如果您需要多索引,只需将 set_indexappend=True 链接起来

    df.set_index('Val').loc[df.Val.value_counts().index].set_index('IDs', append=True)
    

    【讨论】:

      【解决方案2】:

      您可以使用np.argsortiloc 来避免冗长的sort_values

      s = np.argsort(-df.groupby('Val')['IDs'].transform('size'))
      
      df.iloc[s].set_index(['Val', 'IDs'])
      

      Val IDs
      foo a
          c
          g
          h
      bar b
          e
          f
      abc d
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-19
        • 2021-10-03
        • 2021-08-10
        • 2017-03-27
        • 2017-01-12
        • 2023-03-23
        相关资源
        最近更新 更多