[英]keep second level of multi-index intact while sorting on first one pandas python
I have sorted my first level of index using the following method : Custom sort order function for groupby pandas python 我已经使用以下方法对第一级索引进行了排序 : groupby pandas python的自定义排序顺序函数
def my_func(group):
return sum(group["B"]*group["C"])
idx=df.groupby('A').apply(my_func).reindex(df.index.get_level_values(0))
df.iloc[idx.argsort()]
The issue is that the second level ordering is jumbled up after sorting on the first. 问题在于,第二级排序在对第一级进行排序后变得混乱。 How can I make sure that the intra-group order is kept ?
如何确保组内订单得到保留?
from 从
A B C
1 0 1 8
1 3 3
2 0 1 2
1 2 2
3 0 1 3
1 2 4
to 至
A B C
2 0 1 2
1 2 2
3 0 1 3
1 2 4
1 0 1 8
1 3 3
and not (last 2 lines inverted) 而不是(倒数2行)
A B C
2 0 1 2
1 2 2
3 0 1 3
1 2 4
1 1 3 3
0 1 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.