【问题标题】:Pandas groupby count number of daysPandas groupby 计算天数
【发布时间】:2020-08-31 19:56:48
【问题描述】:

假设我有以下数据框:

df = pd.DataFrame({'c': ['abc', 'def', 'wyx', 'abc', 'wyx'], 'begin_date': ['2020-01-01', '2000-12-23', '2003-07-07', '2005-03-02', '2004-01-01'], 'end_date': ['2020-01-31', '2001-02-02', '2004-03-02', '2005-04-01', '2004-07-04']})

df

  c  begin_date    end_date
 abc  2020-01-01  2020-01-31
 def  2000-12-23  2001-02-02
 wyx  2003-07-07  2004-03-02
 abc  2005-03-02  2005-04-01
 wyx  2004-01-01  2004-07-04

我想按 c 分组并计算该 c 的一行在 begin_date 和 end_date 之间的唯一天数,我的最终数据框将是:

end = pd.DataFrame({'c': ['abc', 'def', 'wyx'], 'count': [30, 41, 363]})

end
   c  count
 abc     30
 def     41
 wyx    363

【问题讨论】:

    标签: python pandas dataframe datetime


    【解决方案1】:

    首先要转换成datetime类型,然后可以减法和groupby:

    s = (pd.to_datetime(df.end_date) - pd.to_datetime(df.begin_date)).dt.days
    s.groupby(df['c']).sum()
    

    更新:要删除重复的天数,我们可以重新采样:

    df['begin_date'] = pd.to_datetime(df['begin_date'])
    df['end_date'] = pd.to_datetime(df['end_date'])
    
    (pd.concat(pd.DataFrame({
        'c':x['c'],
        'count':pd.date_range(x.begin_date, x.end_date)
    }) for _,x in df.iterrows())
       .drop_duplicates()
       .groupby('c').size()
       .reset_index(name='count')
    )
    

    输出:

         c  count
    0  abc     62
    1  def     42
    2  wyx    364
    

    【讨论】:

    • 如果没有重叠间隔,这将起作用,但是,例如,对于wyx,间隔重叠,它将是 363 而不是 424
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2018-08-24
    • 2017-01-26
    相关资源
    最近更新 更多