【问题标题】:Sum total hours and minutes for each userprofileid with Python使用 Python 对每个 userprofileid 的总小时数和分钟数求和
【发布时间】:2021-10-08 07:50:35
【问题描述】:

我想为每个userprofileid 获得totalhourstotalminutes 的数量。
例如:

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()

【问题讨论】:

标签: python pandas data-science


【解决方案1】:

您可以使用分组依据并对值求和


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

【讨论】:

  • 嗨,伙计!谢谢您的帮助!但是,如果我想用这些变量创建另一列?我可以做 df["new"] = df.groupby('userprofileid').sum().reset_index()).to_string(index=False) 吗?
  • 你想创建一个新的df而不修改现有的df?
  • 是的,我想修改我的 df,但我想再创建 2 列:work_hours 和 work_minutes
  • 我已编辑我的答案以将结果保存在新的 df 中。请看看这是不是你想要的
  • 完美!我意识到我不能创建一个新列,因为我的行数较少。谢谢大佬!
猜你喜欢
  • 1970-01-01
  • 2016-08-27
  • 2017-03-17
  • 2019-02-22
  • 2023-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多