首页 > 解决方案 > 使用 Python 对每个 userprofileid 的总小时数和分钟数求和

问题描述

我想得到我所拥有的数量totalhourstotalminutes数量userprofileid
例如:

userprofileid      totalhours    totalminutes
453                7.0           420
120                7.5           450
453                8.0           480

我无法删除userprofileid,因为每个 ID 都有其小时和分钟。
我试过这个,但我得到了小时和分钟的总数,并将它们添加到每一行中。

for user in clocking_left["userprofileid"]:
clocking_left["user_minutes_total"] = clocking_left["totalminutes"].sum()
clocking_left["user_hours_total"] = clocking_left["hours"].sum()

标签: pythonpandasdata-science

解决方案


您可以使用 group by 并总结值


import pandas as pd

data = {'userprofileid': [453,120,453],
        'totalhours': [7.0,7.5,8],
'totalminutes': [420,450,480]       
}

df = pd.DataFrame(data, columns = ['userprofileid','totalhours','totalminutes'])

df_new = df.groupby('userprofileid').sum().reset_index()

print(df_new.to_string(index=False))

输出

userprofileid  totalhours  totalminutes
           120         7.5           450
           453        15.0           900

推荐阅读