gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:38:50 25 4
gpt4 key购买 nike

我有一个时间序列,我将其重新采样到此数据帧 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(pd.date_range(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)

关于python - pandas-更改重新采样时间序列的开始和结束日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45908146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com