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

spa*_*e12 4 python datetime time-series 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
Run Code Online (Sandbox Code Playgroud)

我需要做的

开始日期: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
Run Code Online (Sandbox Code Playgroud)

是否有一种有效的方法来执行此操作.我能想到的唯一方法就是没那么有效.我从昨天开始尝试这个.请帮忙

  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']
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 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)
Run Code Online (Sandbox Code Playgroud)

  • 正如[此处](/sf/answers/4373865121/)所述,DateTimeIndex 不再接受“start”和“end”参数。`date_range` 可以用来完成同样的事情(即 `pd.DatetimeIndex(pd.date_range(start='2009-06-01', end='2009-06-30 23:00:00), freq=" 1小时")`) (2认同)