Pandas改变重采样时间序列的开始和结束日期

2024-05-08 07:23:15 发布

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

我把一个时间序列重新采样到这个数据帧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-30 23:00:00

所以数据应该是这样的:

^{pr2}$

有没有一种有效的方法来完成这个任务。我唯一能想到的方法不是那么有效。我从昨天开始就在试这个。请帮忙

  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']

Tags: 数据方法dfindexcount时间zeros序列
1条回答
网友
1楼 · 发布于 2024-05-08 07:23:15

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

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)

相关问题 更多 >