Python 数据操作-值为字母数字时对索引进行排序
我想知道我应该如何处理这种数据操纵困境。 在索引级别上的值为字母数字的数据框中,对多索引的索引进行排序的最佳方法是什么。 这些数值是:Python 数据操作-值为字母数字时对索引进行排序,python,pandas,sorting,dataframe,indexing,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'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\u 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)
您想对第0级还是第1级进行排序?第1级在我的案例中是持续时间这是我看到的代码
c=sorted(ns.natsorted(df_with_col_arg),key=lambda x:not x.isdigit())AttributeError:“tuple”对象没有属性“isdigit”
@OAKc=df.columns.levels[0]
你能试试这个吗?@COLDSPEED我写错了。现在已更正,但现在这一行df=df。reindex\u轴(c,轴=1)
显示TypeError:Expected tuple,got str
。其中C为列表类型。试图将C转换为元组,但返回了相同的错误。@请打印df.columns
并将结果添加到问题中好吗?这会有帮助的。@COLDSPEED-非常感谢!它工作得非常好,非常棒!