pandas 中的多索引排序 [英] Multi Index Sorting in Pandas
问题描述
我在pandas df中有一个包含多索引列的数据集,我想按特定列中的值进行排序.我尝试使用sortindex和sortlevel,但无法获得所需的结果.我的数据集如下:
I have a dataset with multi-index columns in a pandas df that I would like to sort by values in a specific column. I have tried using sortindex and sortlevel but haven't been able get the results I am looking for. My dataset looks like:
Group1 Group2
A B C A B C
1 1 0 3 2 5 7
2 5 6 9 1 0 0
3 7 0 2 0 3 5
我想按降序按组1中的C列对所有数据和索引进行排序,因此我的结果如下所示:
I want to sort all data and the index by column C in Group 1 in descending order so my results look like:
Group1 Group2
A B C A B C
2 5 6 9 1 0 0
1 1 0 3 2 5 7
3 7 0 2 0 3 5
是否可以对数据所在的结构进行这种排序,还是应该将Group1交换到索引端?
Is it possible to do this sort with the structure that my data is in, or should I be swapping Group1 to the index side?
推荐答案
按MultiIndex排序时,您需要包含用于描述列表中列的元组*:
When sorting by a MultiIndex you need to contain the tuple describing the column inside a list*:
In [11]: df.sort_values([('Group1', 'C')], ascending=False)
Out[11]:
Group1 Group2
A B C A B C
2 5 6 9 1 0 0
1 1 0 3 2 5 7
3 7 0 2 0 3 5
* ,以免使大熊猫误以为您想先按Group1然后按C进行排序.
注意:最初使用 .sort
,因为它已过时,然后在0.20中删除,因此推荐使用 .sort_values
.
Note: Originally used .sort
since deprecated then removed in 0.20, in favor of .sort_values
.
这篇关于 pandas 中的多索引排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!