简体   繁体   English

具有多索引的熊猫中的自定义排序顺序

[英]Custom Sort Order in Pandas with Multiindex

I have a dataset with multiindex, where level 0 is the following: 我有一个具有multiindex的数据集,其中级别0如下:

['-67', '67', '-68', '68']

when importing the data through a java interface, the data loads in this order: 通过Java接口导入数据时,数据将按以下顺序加载:

['-67', '-68', '67', '68']

I plan on appending the timestamps from each level 0 index, so having them in the correct order is important. 我计划从每个0级索引附加时间戳,因此以正确的顺序排列它们很重要。 The correct order is: 正确的顺序是:

['-##', '##', .....] for as many level 0 datasets are being analyzed. 正在分析许多0级数据集的['-##', '##', .....]

This also needs to be a generic solution, as it will involve many datasets. 这也需要成为通用解决方案,因为它将涉及许多数据集。

I've looked at the solutions for custom sorting, but nothing provided a generic solution. 我看过自定义排序的解决方案,但没有提供通用解决方案。

You can using sorted with key and lambda 您可以使用keylambda sorted

sorted(['-67', '-68', '67', '68'],key= lambda x : abs(int(x)))
Out[882]: ['-67', '67', '-68', '68']

如果要确保负数出现在正数之前,可以执行以下操作:

sorted(list_name, key = lambda x : (abs(int(x), int(x) > 0)))

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

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