简体   繁体   English

使用级别中的唯一值重新索引 MultiIndex

[英]Reindex MultiIndex with unique values in level

I have this dataframe:我有这个 dataframe:

df = pd.DataFrame({'NUMBER_1': {('2019-07', 'A'): 4, ('2019-07', 'D'): 2, ('2019-08', 'A'): 32, ('2019-08', 'B'): 14, ('2019-09', 'A'): 32, ('2019-09', 'B'): 53, ('2019-09', 'C'): 54, ('2019-09', 'D'): 24},
 'NUMBER_2': {('2019-07', 'A'): 75, ('2019-07', 'D'): 12, ('2019-08', 'A'): 42, ('2019-08', 'B'): 32, ('2019-09', 'A'): 54, ('2019-09', 'B'): 21,  ('2019-09', 'C'): 97, ('2019-09', 'D'): 65}})

df : df

在此处输入图像描述

Where I'm looking for this output:我在哪里寻找这个 output:

在此处输入图像描述

I have seen similar questions for categorical types columns, but not for indexes and I'm looking for a way to avoid using the method reset_index() as actually I'm using four indexes and not just two as in the minimal example.我已经看到关于分类类型列的类似问题,但不是针对索引,我正在寻找一种避免使用方法reset_index()的方法,因为实际上我使用的是四个索引,而不是最小示例中的两个索引。 Any suggestions?有什么建议么?

You can define a MultiIndex using the current MultiIndex.levels , and reindex setting fill_value to 0 :您可以使用当前的MultiIndex.levels MultiIndex并将fill_value reindex设置为0

df.reindex(pd.MultiIndex.from_product(df.index.levels), fill_value=0)

              NUMBER_1  NUMBER_2
2019-07 A         4        75
        B         0         0
        C         0         0
        D         2        12
2019-08 A        32        42
        B        14        32
        C         0         0
        D         0         0
2019-09 A        32        54
        B        53        21
        C        54        97
        D        24        65

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

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