Michel
Michel

Reputation: 33

Python - Pandas - resample issue

I am trying to adapt a Pandas.Series with a certain frequency to a Pandas.Series with a different frequency. Therefore I used the resample function but it does not recognize for instance that 'M' is a subperiod of '3M' and raised an error

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

Raises the following exception:

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

This seems to be due to the pd.tseries.frequencies.is_subperiod function:

import pandas as pd

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

Indeed it returns False for the first command and True for the second.

I would really appreciate any hints about any solution.

Thks.

Upvotes: 3

Views: 912

Answers (1)

cosmic_inquiry
cosmic_inquiry

Reputation: 2684

Try changing from PeriodIndex to DateTimeIndex before resampling:

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

Output:

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

Upvotes: 1

Related Questions