pandas -更改重新采样的时间序列的开始和结束日期 [英] pandas- changing the start and end date of resampled timeseries

查看:29
本文介绍了 pandas -更改重新采样的时间序列的开始和结束日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重新采样到此数据帧中的时间序列df

我的数据是从6月6日到6月28日。它希望将数据从6月1日延长到6月30日。Count列将仅在延长期间内具有0值,而我的实际值将在第6到28天内具有。

Out[123]: 
                         count
Timestamp                    
2009-06-07 02:00:00         1
2009-06-07 03:00:00         0
2009-06-07 04:00:00         0
2009-06-07 05:00:00         0
2009-06-07 06:00:00         0

我需要制作

开始日期:2009-06-01 00:00:00

结束日期:2009-06-30 23:00:00

因此数据将如下所示:

                         count
Timestamp                    
2009-06-01 01:00:00         0
2009-06-01 02:00:00         0
2009-06-01 03:00:00         0

有没有一种有效的方法来实现这一点。我唯一能想到的办法不是那么有效,我从昨天就开始试了。请帮帮忙

  index = pd.date_range('2009-06-01 00:00:00','2009-06-30 23:00:00', freq='H')
    df = pandas.DataFrame(numpy.zeros(len(index),1), index=index)
    df.columns=['zeros']
    result= pd.concat([df2,df])
    result1= pd.concat([df,result])
    result1.fillna(0)
    del result1['zero']

推荐答案

您可以创建具有所需开始日期/时间和结束日期/时间的新索引,重新采样时间序列数据并按计数聚合,然后将索引设置为新索引。

import pandas as pd

# create the index with the start and end times you want
t_index = pd.DatetimeIndex(start='2009-06-01', end='2009-06-30 23:00:00', freq='1h')

# create the data frame
df = pd.DataFrame([['2009-06-07 02:07:42'],
                   ['2009-06-11 17:25:28'],
                   ['2009-06-11 17:50:42'],
                   ['2009-06-11 17:59:18']], columns=['daytime'])
df['daytime'] = pd.to_datetime(df['daytime'])

# resample the data to 1 hour, aggregate by counts,
# then reset the index and fill the na's with 0
df2 = df.resample('1h', on='daytime').count().reindex(t_index).fillna(0)

更新:

原来的答案已经贬值,需要您按照@toni-penya-alba的建议将第一行代码更改为:

t_index = pd.DatetimeIndex(pd.date_range(start='2009-06-01', end='2009-06-30 23:00:00', freq="1h"))

这篇关于 pandas -更改重新采样的时间序列的开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆