我有这样一个数据帧:
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
,它稍后会被删除?你知道吗
使用
set_index
和value_counts
如果您需要多索引,只需将
set_index
与append=True
链相加即可您可以使用
np.argsort
和iloc
来避免冗长的sort_values
相关问题 更多 >
编程相关推荐