按多个列分组,其中一些具有单个值(在Python中)

时间:2020-11-04 03:15:04

标签: python pandas numpy

我有一个数据集df,我希望在其中对类型以及日期进行求和和分组:

 date        size       type

1/1/2020     1          a
1/1/2020     1          a
1/1/2020     1          a
1/1/2020     2          b
1/1/2020     5          b
1/1/2020     6          b
1/1/2020     1          c
2/1/2020     20         a
2/1/2020     21         a
2/1/2020     10         a
2/1/2019     1          b
2/1/2019     4          b     
2/1/2019     5          b

所需的输出

(grouping by type and date to find sum)

  date      size                type
 1/1/2020   3                   a
 1/1/2020   13                  b
 1/1/2020   1                   c
 2/1/2020   51                  a
 2/1/2019   10                  b

这就是我在做什么:

 a.groupby(['type','date']).sum() 

但是,由于在整个数据帧中未显示该类型,因此输出不是所需的输出。这就是我得到的:

enter image description here

任何建议都值得赞赏。

我遇到的问题是:

date       size                type
1/1/2020   1                   c

因为只存在一个值。

1 个答案:

答案 0 :(得分:2)

操作时:

 a.groupby(['type','date']).sum() 

您将获得一个具有MultiIndex的新数据框:typeDate。这就是Pandas决定显示的方式:省略重复的下级索引。第二行仍然有type == 'a'

要匹配您的预期输出,即使typeDate像往常一样具有所有值的列,您可以将以上链接与.reset_index()或使用:

a.groupby(['type','date'], as_index=False).sum()