如何创建根据组大小排序的多索引数据帧?

2024-04-25 20:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

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,它稍后会被删除?你知道吗


Tags: 数据trueidsdataframedfsizefoo排序
2条回答

使用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)

您可以使用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

相关问题 更多 >