Python - Pandas - 重新采样问题

3

我正在尝试将具有一定频率的Pandas.Series适应到具有不同频率的Pandas.Series上。因此,我使用了重新取样函数,但它没有识别出'M'是'3M'的子周期,并引发了错误。

import pandas as pd

idx_1 = pd.period_range('2017-01-01', periods=6, freq='M')
data_1  = pd.Series(range(6), index=idx_1)
data_higher_freq = data_1.resample('3M', kind="Period").sum()

引发以下异常:

Traceback (most recent call last):  File "/home/mitch/Programs/Infrastructure_software/Sandbox/spyderTest.py", line 15, in <module>
data_higher_freq = data_1.resample('3M', kind="Period").sum() File "/home/mitch/anaconda3/lib/python3.6/site-packages/pandas/core/resample.py", line 758, in f return self._downsample(_method, min_count=min_count) File "/home/mitch/anaconda3/lib/python3.6/site-packages/pandas/core/resamplepy", line 1061, in _downsample 'sub or super periods'.format(ax.freq, self.freq))
pandas._libs.tslibs.period.IncompatibleFrequency: Frequency <MonthEnd> cannot be resampled to <3 * MonthEnds>, as they are not sub or super periods

这似乎是由pd.tseries.frequencies.is_subperiod函数引起的:
import pandas as pd

pd.tseries.frequencies.is_subperiod('M', '3M')
pd.tseries.frequencies.is_subperiod('M', 'Q')

第一个命令返回False,第二个命令返回True。关于任何解决方案的提示将不胜感激。

谢谢。


pd.tseries.frequencies.is_subperiod('M', '3M') 在我的电脑上返回了 Nonetype 而不是 bool。但是对我来说重新采样没有问题。我正在运行 Python 3.6。 - Mankind_008
澄清一下,我也在运行Python 3.6和Pandas 0.23.1。 - Michel
1个回答

1

在重新采样之前,尝试将索引从PeriodIndex更改为DateTimeIndex

import pandas as pd

idx_1 = pd.period_range('2017-01-01', periods=6, freq='M')
data_1  = pd.Series(range(6), index=idx_1)
data_1.index = data_1.index.astype('datetime64[ns]')
data_higher_freq = data_1.resample('3M', kind='period').sum()

输出:

data_higher_freq
Out[582]: 
2017-01     3
2017-04    12
Freq: 3M, dtype: int64

非常感谢!我相信我将不得不使用这种操作来在日期时间和周期之间切换。Pandas - Michel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接