python - 数据操作 - 当值为字母数字时排序索引

标签 python pandas sorting dataframe indexing

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

[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”代表年。

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

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

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 包对列进行自然排序。这是一个例子:

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)

关于python - 数据操作 - 当值为字母数字时排序索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47239950/

相关文章:

python - 如何理解Python中list结构的内存?

python - 从 kmeans 聚类了解客户属性

python - 如何根据数据框中以前的值制作一列

python - 我从哪里开始寻找 python 中的图像匹配库?

postgresql - 您是否可以为 ORDER BY 子句使用自定义 Postgres 比较函数?

c - 在链接列表上使用合并排序的段错误

python - 访问 Pandas 数据框时出现关键错误

python - dropEvent() 没有被调用

python - 编写多个 pandas dataframes 到 excel

python - 在 Pandas 上绘制整行