如何正确使用带有水平和轴参数的熊猫sort_index?

问题描述 投票:0回答:1

关于此df:

               Amount                          type                 
Month_year 2019-06-01     2019-07-01     2019-06-01    2019-07-01   
TYPE_ID             1   2          1   2          1  2          1  2
ID                                                                  
100                20  10         40  20          1  1          2  1
200                80  60         30  10          2  2          1  1

以下代码:

df = df.sort_index(axis=1, level=[1,2])

产生此:

               Amount       type     Amount  ...       type     Amount       type
Month_year 2019-06-01 2019-06-01 2019-06-01  ... 2019-07-01 2019-07-01 2019-07-01
TYPE_ID             1          1          2  ...          1          2          2
ID                                           ...                                 
100                20          1         10  ...          2         20          1
200                80          2         60  ...          1         10          1

我真的不明白发生了什么。我已经读过the docs,但是没有示例,并且说明确实晦涩。

任何人都可以向我解释此方法如何工作以及如何收到此结果吗?

python pandas
1个回答
0
投票

基本上是

[sort_indexaxis=1一起对列标题进行排序,然后使用此顺序来设置列的顺序。

并且,推论,

[sort_indexaxis=0一起对索引进行排序,然后使用此顺序来设置行的顺序。


这是您的输入df的样子:

enter image description here

上图中的前三个“行”对应于df的熊猫MultiIndex列,如下所示:

df.columns
MultiIndex([('Amount', '2019-06-01', 1),
            ('Amount', '2019-06-01', 2),
            ('Amount', '2019-07-01', 1),
            ('Amount', '2019-07-01', 2),
            (  'type', '2019-06-01', 1),
            (  'type', '2019-06-01', 2),
            (  'type', '2019-07-01', 1),
            (  'type', '2019-07-01', 2)])

假装您的3级multiIndex列被神奇地转换为DataFrame,每个级别都有其自己的称为cdf的列:

cdf
    level_0     level_1  level_2
(1)  Amount  2019-06-01        1
(2)  Amount  2019-06-01        2
(3)  Amount  2019-07-01        1
(4)  Amount  2019-07-01        2
(5)    type  2019-06-01        1
(6)    type  2019-06-01        2
(7)    type  2019-07-01        1
(8)    type  2019-07-01        2

这里的行号对应于原始DataFrame中的列标识符。让我们看看当我们按最后两列对cdf进行排序时会发生什么:

cdf.sort_values(['level_1', 'level_2'])

    level_0     level_1  level_2
(1)  Amount  2019-06-01        1
(5)    type  2019-06-01        1
(2)  Amount  2019-06-01        2
(6)    type  2019-06-01        2
(3)  Amount  2019-07-01        1
(7)    type  2019-07-01        1
(4)  Amount  2019-07-01        2
(8)    type  2019-07-01        2

注意已排序的cdf的索引:

(1) (5) (2) (6) (3) (7) (4) (8)

现在让我们看看将sort_values操作应用于df时会发生什么:

df.sort_index(level=[1, 2], axis=1)

enter image description here

中间的省略号表示不是所有的列都可以显示(实际上,第(6)和(3)列没有显示,但是它们在那里很多),但这不是有趣的部分。将此与cdf的顺序进行对比。

© www.soinside.com 2019 - 2024. All rights reserved.