Skip to main content
 首页 » 编程设计

python之为什么 pandas 时间序列重新采样会引发不兼容的频率错误

2025年01月19日1052php

问题

我有一个带有 time series 的 pandas DataFrame从 2006 年开始五年的数据,我添加了一个 PeriodIndex,它是从使用 pd.period_range() 制作的 Period 自动转换而来的如下面的代码块所示。

那里,我要resample()前四年,我用过 time series offset aliases在docs中提到.当我使用 freq=1W 时它可以工作,但是例如频率为 2(或同样为 3 周)我收到一条错误消息

IncompatibleFrequency: Input has different freq=2W-SUN from PeriodIndex(freq=W-SUN) 

在 Periods part of the time series docs 中提到它说:

Adding and subtracting integers from periods shifts the period by its own frequency. Arithmetic is not allowed between Period with different freq (span).

老实说,我不确定这与我的问题有什么关系。

错误的一般形式是,如果我的 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 类型 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,它会起作用。 (输入的 freq=6M 与 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" , 但似乎没有其他帖子。

问题

我想了解为什么会出现错误,以及如何解决重新采样到任意周期的问题 - 或者至少了解限制。

请您参考如下方法:

这是 plot() 的错误,而不是 resample(),并且已在 GitHub (#14763) 上报告。

作为修复错误之前的解决方法,您可以使用 to_timestamp 将索引转换为 DatetimeIndex绘图之前:

df.loc['2006':'2009', 'A'].resample('2W').mean().to_timestamp().plot() 

请注意,您可能需要调整to_timestamp 的freq 或how 参数。有关这些参数的更多详细信息,请参阅文档。