pandas-更改重采样时间序列的开始和结束日期

时间:2017-08-27 18:37:57

标签: python pandas datetime time-series

我有一个时间序列,我重新采样到此数据框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']

2 个答案:

答案 0 :(得分:5)

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

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)

答案 1 :(得分:0)

DatetimeIndex()不再与这些参数一起使用,引发__new__() got an unexpected keyword argument 'start'

相关问题