【问题标题】:Groupby sum by Inspector_ID, and Day in pandas按 Inspector_ID 分组总和,以及熊猫中的 Day
【发布时间】:2020-03-13 01:28:14
【问题描述】:

我有一个如下所示的数据框。两个检查员在不同的日子里走过的距离。

Inspector_ID      Timestamp                  Distance
    1              2018-07-24 7:31:00          0
    1              2018-07-24 7:31:01          2.3
    1              2018-07-24 7:33:01          2.8
    1              2018-07-25 7:32:04          0
    1              2018-07-25 7:33:06          3.6
    2              2018-07-20 8:35:08          0
    2              2018-07-20 8:36:10          5.6
    2              2018-07-20 8:37:09          2.1
    2              2018-07-27 8:38:00          0
    2              2018-07-27 8:39:00          3
    2              2018-07-27 8:40:00          2.6

从上面,我想准备下面的数据框

预期输出

Inspector_ID   Day_of_the_month   Total_distance   No.of_entries_in that_day  week_of_the_month
1              24                 5.1              3                          4
1              25                 3.6              2                          4
2              20                 7.7              3                          3
2              27                 5.6              3                          4

【问题讨论】:

  • 您有仅 1 个月的数据吗?否则也应该有一个月的专栏?
  • @anky_91 不,其他月份的数据我也有,这个时候我们就当做一年的数据吧。假设数据仅为 1 年。

标签: pandas datetime pandas-groupby


【解决方案1】:
    import pandas as pd

    from datetime import datetime as dt
    df={"Inspector_ID":[1,1,1,1,1,2,2,2,2,2,2]     ,"Timestamp" :["2018-07-24 7:31:00" ,"2018-07-24 7:31:01" ,"2018-07-24 7:33:01" ,"2018-07-25 7:32:04" ,"2018-07-25 7:33:06","2018-07-20 7:31:00" ,"2018-07-20 8:36:10" ,"2018-07-20 8:37:09","2018-07-27 8:38:00" ,"2018-07-27 8:39:00","2018-07-27 8:38:00"],"Distance":[0,2.3,2.8,0,3.6,0,5.6,2.1,0,3,2.6]}

    df["Day"]=[]
    df["week_of_month"]=[]

    for entry in df["Timestamp"]:  
        df["Day"].append(dt.strptime(entry,'%Y-%m-%d %H:%M:%S').day)
        df["week_of_month"].append((dt.strptime(entry,'%Y-%m-%d %H:%M:%S').day - 1) // 7 + 1)

    df=pd.DataFrame(df)

    result=df.groupby(['Inspector_ID','Day','week_of_month'])['Distance'].agg({"totdist":"sum","NoEntries":"count"})
    print(result)

【讨论】:

  • 首先创建数据框到字典以应用逻辑
猜你喜欢
  • 2017-02-06
  • 2022-06-22
  • 2020-10-12
  • 2021-04-24
  • 2020-09-04
  • 2016-02-20
  • 2021-01-06
  • 2021-08-25
  • 2020-02-21
相关资源
最近更新 更多