数据操作 - 当值为字母数字时对索引进行排序 [英] Data Manipulation - Sort Index when values are Alphanumeric

查看:116
本文介绍了数据操作 - 当值为字母数字时对索引进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何处理这种数据操作困境。
在数据框中对多索引的索引进行排序的最佳方法是什么,其中索引的on级别的值是字母数字。
值是:

I'm wondering how I should approach this data manipulation predicament. What is the best method to sort an index of a multi-index in a data frame where the values of on level of the index is alphanumeric. The values are:

[u'0',u'1',u'10',u'11', u'2',u'2Y',u'3',u'3Y',u'4',u'4Y',u'5',u'5Y',u'6',u'7', u'8',u'9',u'9Y']

我要搜索的结果是:

[u'0',u'1',u'2',u'3',u'4',u'5',u' 6',u'7',u'8',u'9',u'10',u'11',u'2Y',u'3Y',u'4Y',u'5Y',u' 9Y']

纯数值代表数月,而整数加'Y'代表数年。

The plain numeric values stand for months while the integer plus 'Y' stand for years.

有没有办法对索引进行排序?

Is there a way to sort the index?

持续时间 - 是多指数的一个级别,第二个是和。
请在下面找到一个示例数据集:

Duration - is one level of the multi index, the second is sum. Please find a sample dataset below:

Duration                            2          2Y         3         3Y   
customer                                                                     
Invoice A                         25.50        0.00      0.00       20.00   
Invoice B                         50.00        25.00     -10.50     0.00
Invoice C                         125.00       0.00      11.20      0.50
Invoice D                         0.00        15.00      0.00       80.10


推荐答案

您可以使用 natsort 包自然地对列进行排序。这是一个例子:

You can use the natsort package to naturally sort your columns. Here's an example:

import natsort as ns

c =  ['0', '1', '10', ...]
c = sorted(ns.natsorted(c), key=lambda x: not x.isdigit())

print(c)
['0',
 '1',
 '2',
 '3',
 '4',
 '5',
 '6',
 '7',
 '8',
 '9',
 '10',
 '11',
 '2Y',
 '3Y',
 '4Y',
 '5Y',
 '9Y']






对于您的问题,类似的方法是使用 reindex_axis 作为额外步骤:

c = df.columns.levels[1]
c = sorted(ns.natsorted(c), key=str.isdigit, reverse=True)

df = df.reindex_axis(pd.MultiIndex.from_product([df.columns.levels[0], c]), axis=1)

这篇关于数据操作 - 当值为字母数字时对索引进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆