pandas- changing the start and end date of resampled timeseries( pandas -更改重新采样的时间序列的开始和结束日期)
本文介绍了 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 -更改重新采样的时间序列的开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:pandas -更改重新采样的时间序列的开始和结束日期


基础教程推荐
猜你喜欢
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01