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

2024-05-16 13:16:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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>;结束日期

使用python解决这个问题的正确方法是什么?有我可以利用的图书馆吗


Tags: inputoutputvalue时间序列计数abc帐户名
1条回答
网友
1楼 · 发布于 2024-05-16 13:16:43

我认为您需要首先将值转换为datetimes,然后在列表理解中使用^{},最后使用^{}

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

如果需要数据帧:

df1 = s.rename_axis('date').reset_index(name='value')

相关问题 更多 >