简体   繁体   English

在第一个熊猫python上排序时,保持第二级的多索引完整

[英]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

I think you need stable sorting algo - mergesort : 我认为您需要稳定的排序算法 mergesort

idx=df.index.get_level_values(0).map(df.groupby('A').apply(my_func))
df = df.iloc[idx.argsort(kind='mergesort')]
print (df)
     B  C
A        
2 0  1  2
  1  2  2
3 0  1  3
  1  2  4
1 0  1  8
  1  3  3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM