简体   繁体   English

在不重置索引的情况下填充 Pandas 空白 groupby 行

[英]Fill pandas blank groupby rows without resetting the index

Hi I have a table like this after group by:嗨,我在分组后有一张这样的桌子:

t = df.loc[(year-3 <= year) & (year <= year-1), 'Net Sum'].groupby([month, association]).sum()


t
 YearMonth  Type
    1          Other                  27471.73
               base               -14563752.74
               plan                16286620.30
    2          Other                 754691.36
               base                30465722.53
               plan                17906687.29
    3          Other                  20285.92
               base                29339325.21
               plan                15492558.91

How can I fill the blanks with grouped Year Month without resetting the index as I'd like to keep YearMonth as index?如何在不重置索引的情况下用分组的 Year Month 填充空白,因为我想保留 YearMonth 作为索引?

Expected Outcome.预期结果。

t
 YearMonth  Type
    1          Other                  27471.73
    1          base               -14563752.74
    1          plan                16286620.30
    2          Other                 754691.36
    2          base                30465722.53
    2          plan                17906687.29
    3          Other                  20285.92
    3          base                29339325.21
    3          plan                15492558.91

I think this can only be achieved by altering the display option:我认为这只能通过更改显示选项来实现:

with pd.option_context('display.multi_sparse', False):
    print(t)

If we refer the docs如果我们参考文档

display.multi_sparse True “Sparsify” MultiIndex display (don't display repeated elements in outer levels within groups) display.multi_sparse True “Sparsify” MultiIndex 显示(不显示组内外层重复元素)

Hence we can set this to False.因此,我们可以将其设置为 False。

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

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