从开始日期和结束日期创建时间序列

时间:2021-03-24 09:35:52

标签: python pandas time-series

我想从包含订阅开始和结束日期的表中创建一个时间序列。输入表包含订阅的帐户名称及其各自的开始和结束日期。

input:
    accountname    startDate    endDate
     abc          31/12/2020   2/1/2021
     xyz          2/1/2021     4/1/2021
     pqr          4/1/2021     6/1/2021 
     stu          2/1/2021     3/1/2021

时间序列的值将是当天活动的 accountname 的计数,即在其各自的开始和结束日期内的 accountname 的计数。

output:

    TSDate          value (count of active subscriptions)
    1/1/2021       1
    2/1/2021       3
    3/1/2021       2
    4/1/2021       2  

我可以想到通过创建一系列日期并每次迭代输入来确定 TSdate>endDate 的记录数来解决这个问题。

使用 python 解决这个问题的正确方法是什么?有没有我可以利用的库?

1 个答案:

答案 0 :(得分:2)

我认为您需要先将值转换为日期时间,然后在列表理解中使用 concat,最后使用 Index.value_counts

df['startDate']= pd.to_datetime(df['startDate'], dayfirst=True)
df['endDate']= pd.to_datetime(df['endDate'], dayfirst=True)

s = (pd.concat([pd.Series(r.accountname,pd.date_range(r.startDate, r.endDate)) 
               for r in df.itertuples()])
       .index
       .value_counts()
       .sort_index())
print (s)
2020-12-31    1
2021-01-01    1
2021-01-02    3
2021-01-03    2
2021-01-04    2
2021-01-05    1
2021-01-06    1
dtype: int64

如果需要DataFrame:

df1 = s.rename_axis('date').reset_index(name='value')
相关问题