【问题标题】:How do the sum of a column with group by date from datetime ? Python Pandas如何从 datetime 按日期分组列的总和?蟒蛇熊猫
【发布时间】:2021-02-09 11:13:14
【问题描述】:

我想按日期对列持续时间组求和,但在这段 df 中列开始和结束是日期时间:

begin                       end                         duration
2020-10-14 19:17:52.724020  2020-10-14 19:21:40.179003  227.45
2020-10-14 19:21:40.179003  2020-10-14 19:21:44.037103  3.86
2020-10-14 19:59:27.183161  2020-10-14 20:00:43.847816  76.66
2020-10-14 20:00:43.847816  2020-10-14 20:00:43.847822  0
2020-10-14 20:02:14.341240  2020-10-14 23:59:59.900000  14265.56
2020-10-15 00:00:00.000000  2020-10-15 05:25:32.935971  19532.94
2020-10-15 05:25:32.935971  2020-10-15 05:25:33.068959  0.13

df.info()

begin       41763 non-null  datetime64[ns] 
end         41763 non-null  datetime64[ns] 
duration    41763 non-null  float64   

结果必须是:

begin         duration
2020-10-14    14,573.53
2020-10-15    19,533.07

所以我尝试了我所有的 df,但它在某些日期有效,而在其他日期无效。因为我对 excel 做同样的事情,而在某个日期我得到了不同的结果。

import pandas as pd
import datetime

df = df.groupby(df['begin_'].dt.date)['duration_'].sum()/3600

【问题讨论】:

  • this but its works for certain date and no for other. - 你能添加一些不工作的行吗?
  • 是的,但是在我需要删除它之后
  • 我不能它太大了......
  • 您需要提出问题的minimal reproducible example,否则这似乎无法重现

标签: python pandas datetime pandas-groupby


【解决方案1】:

您可以使用日期时间对象的date 方法。将其应用于列,您将获得日期。之后分组就好了。

def reduce_to_date(value):
    return value.date()

df['begin'] = df['begin'].apply(reduce_to_date)

df.groupby('begin')['duration'].sum()/3600

【讨论】:

    【解决方案2】:

    第一步是将您拥有的时间戳中的时间和日期分开。我在下面给出示例,其中日期的定义方式与您在数据框中定义的方式相同。

    0   2018-07-02 10:54:00 227.45
    1   2018-07-02 10:54:00 3.86
    2   2018-07-02 10:54:00 76.66
    3   2018-07-02 10:54:00 14265.56
    4   2018-07-02 10:54:00 19532.94
    
    
    d ={'DATA':['2018-07-02 10:54:00','2018-07-02 10:54:00' , '2018-07-02 10:54:00' , '2018-07-02 10:54:00' ,'2018-07-02 10:54:00'],'duration': [227.45,3.86,76.66,14265.56,19532.94]}  
    DF = df.assign(Date=df.Date.dt.date, Time=df.Date.dt.time, Duration = df.duration)
    

    下一步是 groupby 你这样做的方式,但简单地提供有关你分组的变量的信息:

    DF.groupby(['Date']).sum()
    

    给了

    Date        Duration     duration
    2018-07-02  34106.47    34106.47
    

    【讨论】:

    • 嗯,它的工作原理和df.groupby(df['begin_'].dt.date)['duration_'].sum()一样,没必要这样做
    • 你能挑出你的方法(你的和我的)不起作用的部分数据框(假设我们的方法是重复的)。是否可以让一些begin 开始某一天但end 第二天?
    猜你喜欢
    • 2021-02-18
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 2021-11-09
    • 2020-12-16
    • 2021-01-06
    • 2020-02-21
    相关资源
    最近更新 更多