如何使用 Pandas 对两列进行分组并计算行的总和? [英] How to groupby two columns and calculate the summation of rows using Pandas?

查看:470
本文介绍了如何使用 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

这篇关于如何使用 Pandas 对两列进行分组并计算行的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆