如何使用 Pandas 对两列进行分组并计算行的总和?

问题描述:

我有一个熊猫数据框 df 像:

I have a pandas data frame df like:

Name  Hour Activity
    A   4   TT
    A   3   TT
    A   5   UU
    B   1   TT
    C   1   TT
    D   1   TT
    D   2   TT
    D   3   UU
    D   4   UU

如果行具有与 NameActivity 列相同的值,则下一步是求和.

The next step is to get the summation if the rows have identical value of the column Name and Activity.

例如,对于Name: AActivity: TT 的情况,将给出7

For example, for the case Name: A and Activity: TT will give the summation of 7

结果如下

    TT  UU
A   7   5
B   1   0
C   1   0
D   3   7

是否可以使用 pandas groupby 来做这样的事情?

Is it possible to do something like this using pandas groupby?

尝试 groupby.sumunstack

df_final = df.groupby(['Name', 'Activity']).Hour.sum().unstack(fill_value=0)

Out[177]:
Activity  TT  UU
Name
A          7   5
B          1   0
C          1   0
D          3   7