【问题标题】:pandas- changing the start and end date of resampled timeseriespandas-更改重新采样时间序列的开始和结束日期
【发布时间】:2018-02-05 01:59:12
【问题描述】:

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

【问题讨论】:

  • 我不明白预期的输出。是只有三排还是你只是贴了头?是不是要到6月30号才行?如果是这样,ser.reindex(idx, fill_value=0) 应该足够了。
  • @ayhan 是的,它应该持续到 6 月 30 日。我的数据是从 6 月 6 日到 6 月 28 日。它想将数据从 6 月 1 日延长到 6 月 30 日。 count 列仅在延长期内将具有 0 值,而我的实际值从 6 日到 28 日。

标签: python pandas datetime time-series


【解决方案1】:

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

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"))

【讨论】:

  • resample 是否有 'on' 参数。我收到此错误,而此代码 TypeError: resample() got an unexpected keyword argument 'on'
  • 啊,重采样的 API 在 pandas 0.19.0 中发生了变化。你可以在早期版本中完成同样的事情,但可能需要更多的时间。
  • 是的,这不再有效。提高Argument 'tuples' has incorrect type (expected numpy.ndarray, got DatetimeArray)
  • here 所述,DateTimeIndex 不再接受 startend 参数。 date_range 可以用来完成同样的事情(即pd.DatetimeIndex(pd.date_range(start='2009-06-01', end='2009-06-30 23:00:00), freq="1h")
【解决方案2】:

DatetimeIndex() 不再适用于这些参数,引发 __new__() got an unexpected keyword argument 'start'

【讨论】:

  • pd.DatetimeIndex(pd.date_range(start='2009-06-01', end='2009-06-30 23:00:00), freq="1h")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2021-11-15
相关资源
最近更新 更多