【发布时间】:2018-07-31 11:16:48
【问题描述】:
问题
从 2006 年开始,我有一个带有 time series 数据的 pandas DataFrame 五年,其中我添加了一个 PeriodIndex,它是从 Periods 自动转换的,由 pd.period_range() 制成,如下面的代码块所示。
在那里,我想resample() 第一年的四年,我使用了docs 中提到的time series offset aliases。当我使用 freq=1W 时,它可以工作,但是例如频率为 2(或同样持续 3 周)我收到一个错误提示
IncompatibleFrequency: Input has different freq=2W-SUN from PeriodIndex(freq=W-SUN)
Periods part of the time series docs 中提到,它说:
在句点中添加和减去整数会使句点按其自身的频率移动。不同频率(跨度)的周期之间不允许进行算术运算。
老实说,我不确定这与我的问题有何关系。
错误的一般形式是,如果我的freq=XY,它给Input has different freq=XY from PeriodIndex(freq=Y),除非X是1。
数据
原始数据集来自具有多列的 csv 文件,但在示例中,我只有一列 A 具有相同的行数。
import pandas as pd
# dummy DataFrame with 87648 rows
df = pd.DataFrame(dict(A=np.random.randint(1, 101, size=87648)))
# Add periods column, set as index
df['time'] = pd.period_range(start='2006-01-01 00:30', freq='30min', end='2011-01-01')
df = df.set_index('time')
现在,如果我在例如ipython type df.index 我得到以下输出:
PeriodIndex(['2006-01-01 00:30', '2006-01-01 01:00', '2006-01-01 01:30',
'2006-01-01 02:00', '2006-01-01 02:30', '2006-01-01 03:00',
'2006-01-01 03:30', '2006-01-01 04:00', '2006-01-01 04:30',
'2006-01-01 05:00',
...
'2010-12-31 19:30', '2010-12-31 20:00', '2010-12-31 20:30',
'2010-12-31 21:00', '2010-12-31 21:30', '2010-12-31 22:00',
'2010-12-31 22:30', '2010-12-31 23:00', '2010-12-31 23:30',
'2011-01-01 00:00'],
dtype='period[30T]', name='time', length=87648, freq='30T')
这似乎符合我的期望,并且与加载它的 csv 文件中的数据相匹配:
- 共有 87648 行。
- 第一个时间戳是 2006-01-01 00:30。
- 最后一个时间戳是 2011-01-01 00:00。
尝试
# This works
df['A'].loc['2006':'2009'].resample('1W').mean().plot()
# This gives error mentioned above
df['A'].loc['2006':'2009'].resample('2W').mean().plot()
进一步:
- 如果我尝试使用
freq=6M,我会遇到同样的问题,但如果我使用freq=1M,它会起作用。 (Input has different freq=6M from PeriodIndex(freq=M)) -
7D也失败了,根据我的预期,它应该与1W相同。
其他想法
显然在某些情况下某些时段不起作用,但对于几年内的半小时数据,我希望可以产生任何较小的频率,例如任意小时数、天数、周数或月数.
根据this answer,以下是更好的方法:
df['A'].resample('D').interpolate()[::7]
但这给了我一个InvalidIndexError: Reindexing only valid with uniquely valued Index objects。 (我假设在阳光节约时间从夏季到冬季的几个小时内存在重复的索引值。)
另外,我的印象是 pandas 旨在为我们做这种“繁重的工作”,并假设更深入的了解将使用户能够在没有这种变通方法的情况下使用它。
虽然有几篇关于重采样的SO帖子,但我搜索了"IncompatibleFrequency"和"Input has different freq",但似乎没有其他帖子。
问题
我想了解为什么会出现错误,以及如何解决重新采样到任意时间段的问题 - 或者至少了解限制。
【问题讨论】:
标签: python pandas time-series resampling