'changing frequency in a pandas SeriesGroupBy
I'm struggling to find a simple way to change a frequency of a pd.Series
that is grouped on some level of a pd.MultiIndex
(so it's a pd.core.groupby.generic.SeriesGroupBy
).
Here's a simple example how this could be done with a standard pd.Series
:
import pandas as pd
dates = pd.date_range('1990','2000',freq='M')
values = range(len(dates))
vec = pd.Series(values,index=dates)
vec.asfreq('D')
Here's what I'd hope would work for a grouped series but it doesn't:
idx = [x//12 for x in values]
midx =pd.MultiIndex.from_arrays([idx,dates], names=['level0','level1'])
vec = pd.Series(values,index=midx)
vec.groupby('level0').asfreq('D')
I know that I could change the index to level1
, change the frequency and group it again but I wonder if there is a better way to do it.
Edit Here's an approach I mentioned above (very crude, i know):
vec_new = vec.groupby('level0').obj\
.reset_index()\
.set_index('level1')\
.asfreq('D',method='ffill')\
.reset_index()
midx = pd.MultiIndex.from_arrays([vec_new['level0'],vec_new['level1']], names=['level0','level1'])
vec_new.index = midx
vec_new.drop(columns = ['level1'],inplace=True)
vec_new.groupby('level0')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|