简体   繁体   English

如何对 Pandas Dataframe 的 MultiIndex 进行自定义排序?

[英]How do I custom sort against a Pandas Dataframe's MultiIndex?

I have a Pandas dataframe that looks like the following.我有一个如下所示的 Pandas dataframe。

data = pd.DataFrame({
    'x': [10, 9, 8, 4],
    'y': [1, 2, 3, 4],
})

data.index = pd.MultiIndex.from_tuples([
    ('high', 'high'), 
    ('high', 'low'), 
    ('low', 'high'), 
    ('low', 'low')
], names=['score', 'grade'])

I want to sort this dataframe based on the 2 index score and grade .我想根据 2 index scoregrade对这个 dataframe 进行排序。 I want the sort such that low comes before high for both index.我想要这样的排序,即两个指数的low先于high How do I do this?我该怎么做呢?

I tried this code below, but only the first index score is sorted as desired.我在下面尝试了这段代码,但只有第一个索引score是根据需要排序的。

data.sort_index(level=[0, 1], key=lambda s: sorted(s, reverse=True))

Any ideas on how to custom sort against multiple indexes?关于如何针对多个索引自定义排序的任何想法? I tried to create a custom sort function to debug.我尝试创建自定义排序 function 进行调试。 Here's my attempt below.下面是我的尝试。

def do_sort(s):
    print(s)
    
    r = pd.Index(sorted(s, reverse=True), name=s.name)
    print(r)
    
    return r

data.sort_index(level=[0, 1], key=do_sort)

The result of the outputs is as expected.输出结果符合预期。 The values are sorted as I have desired.这些值按照我的需要进行排序。

-- before and after for score
Index(['high', 'high', 'low', 'low'], dtype='object', name='score')
Index(['low', 'low', 'high', 'high'], dtype='object', name='score')

-- before and after for grade
Index(['high', 'low', 'high', 'low'], dtype='object', name='grade')
Index(['low', 'low', 'high', 'high'], dtype='object', name='grade')

In actuality, the grade and score are actually of the values of high , medium and low .实际上, gradescore实际上是highmediumlow的值。 I've only done high and low here for brevity.为了简洁起见,我在这里low high Here is the example that really reflects my data.这是真正反映我的数据的示例。

data = pd.DataFrame({
    'x': [10, 9, 8, 7, 6, 5, 4, 3, 1],
    'y': [1, 2, 3, 4, 5, 6, 7, 8, 9],
})

data.index = pd.MultiIndex.from_tuples([
    ('high', 'high'), 
    ('high', 'medium'), 
    ('high', 'low'),
    ('medium', 'high'),
    ('medium', 'medium'),
    ('medium', 'low'),
    ('low', 'high'), 
    ('low', 'medium'),
    ('low', 'low')
], names=['score', 'grade'])

def do_sort(s):
    mapping = {
        'low': 0,
        'medium': 1,
        'high': 2
    }
    
    print(s)
    
    r = [(v, mapping[v]) for v in s]
    r = sorted(r, key=lambda tup: tup[1])
    r = pd.Index([tup[0] for tup in r], name=s.name)
    
    print(r)
    print('-' * 15)
    
    return r

data.sort_index(level=[0, 1], key=do_sort)

The logged output is as follows.记录的 output 如下。 As you can see, I get the ordering right (low, medium, high), but the score index is only sorted as desired.如您所见,我得到了正确的排序(低、中、高),但score索引仅按需要排序。

-- before/after for score
Index(['high', 'high', 'high', 'medium', 'medium', 'medium', 'low', 'low',
       'low'],
      dtype='object', name='score')
Index(['low', 'low', 'low', 'medium', 'medium', 'medium', 'high', 'high',
       'high'],
      dtype='object', name='score')
-- before/after for grade
Index(['high', 'medium', 'low', 'high', 'medium', 'low', 'high', 'medium',
       'low'],
      dtype='object', name='grade')
Index(['low', 'low', 'low', 'medium', 'medium', 'medium', 'high', 'high',
       'high'],
      dtype='object', name='grade')

Try with ascending尝试ascending

out = data.sort_index(ascending=[True,False])
              x  y
score grade       
high  low     9  2
      high   10  1
low   low     4  4
      high    8  3
#data.sort_index(ascending=[False,False])
#              x  y
#score grade       
#low   low     4  4
#      high    8  3
#high  low     9  2
#      high   10  1

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

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