Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas efficient groupby season for every year

I have a multi-year time series an want the bounds between which 95% of my data lie. I want to look at this by season of the year ('DJF', 'MAM', 'JJA', 'SON').

I've tried following:

import pandas as pd
import numpy as np
FRAC_2_TAIL = 0.025
yr_idx = pd.date_range(start='2005-01-30', 
                       end='2008-02-02', freq='D')
data = np.random.rand(len(yr_idx))
df = pd.DataFrame(index=yr_idx, data=data, columns=['a'])
month_num_to_season =   { 1:'DJF',  2:'DJF', 
                          3:'MAM',  4:'MAM',  5:'MAM', 
                          6:'JJA',  7:'JJA',  8:'JJA',
                          9:'SON', 10:'SON', 11:'SON',
                         12:'DJF'}
grouped =  df.groupby(lambda x: month_num_to_season.get(x.month))                      
low_bounds = grouped.quantile(FRAC_2_TAIL)
high_bounds = grouped.quantile(1 - FRAC_2_TAIL) 

it works in the sense of giving:

DJF   0.021284
JJA   0.024769
MAM   0.030149
SON   0.041784

but takes a very long time on my minutely frequency, decade long, data sets.

I can make use of a TimeGrouper to get almost what I want:

gp_time = df.groupby(pd.TimeGrouper('QS-DEC'))
low_bounds = gp_time.agg(lambda x: x.quantile(FRAC_2_TAIL)) 

but we have separate output for each year (with no obvious way to combine quantile limits over the years).

2004-12-01  0.036755
2005-03-01  0.034271
         ...
2007-09-01  0.098833
2007-12-01  0.068948

I've also tried making a freq='QS-DEC' time-series 'DJF', 'MAM' etc. to minimize the dictionary lookups, then upsampling to df.index.freq and grouping on that. It is slow and memory-heavy too.

It seems like I'm missing something obvious.

EDIT

in light of @JohnE's comment

It is the dict lookup in the groupby that is taking time. Using 5 years of minutely data:

%%timeit
grouped =  df.groupby(lambda x: month_num_to_season.get(x.month)) 
> 13.3 s per loop

the quantile calculation is fast:

%%timeit
low_bounds = grouped.quantile(FRAC_2_TAIL)
> 2.94 ms per loop

Adding a season column and grouping on that is similar in overall timing. Again dominated by the dict lookup`:

SEAS = 'season'
%%timeit
df[SEAS] = [month_num_to_season.get(t_stamp.month) for t_stamp in df.index]
> 13.1 s per loop

%%timeit
gp_on_col = df.groupby(SEAS)
> 10000 loops, best of 3: 62.7 µs per loop

%%timeit
gp_on_col.quantile(FRAC_2_TAIL)
> 753 ms per loop

I re-implemented the method of making a quarterly season dataframe to minimize the dict lookups then up-sampling that. This method is now looking like a substantial improvement: I do not know how I had made it so slow before:

SEASON_HALO = pd.datetools.relativedelta(months=4)
start_with_halo = df.index.min() - SEASON_HALO
end_with_halo = df.index.max() + SEASON_HALO
> 84.1 µs per loop

seasonal_idx = pd.DatetimeIndex(start=start_with_halo, end=end_with_halo, freq='QS-DEC')
seasonal_ts = pd.DataFrame(index=seasonal_idx)
> 440 µs per loop

seasonal_ts[SEAS] = [month_num_to_season.get(t_stamp.month) for t_stamp in seasonal_ts.index]
> 1.25 s per loop

seasonal_minutely_ts = seasonal_ts.resample(df.index.freq, fill_method='ffill')
> 5.12 ms per loop

df_via_resample = df.join(seasonal_minutely_ts)
> 47 ms per loop

gp_up_sample = df_via_resample.groupby(SEAS)
> 63.4 µs per loop

gp_up_sample.quantile(FRAC_2_TAIL)
> 834 ms per loop

That is something like 2 sec vs 13 sec for the other methods.

like image 870
Laurence Billingham Avatar asked Oct 27 '25 16:10

Laurence Billingham


1 Answers

In case it helps, I would suggest replacing the following list comprehension and dict lookup that you identified as slow:

month_to_season_dct = {
    1: 'DJF', 2: 'DJF',
    3: 'MAM', 4: 'MAM', 5: 'MAM',
    6: 'JJA', 7: 'JJA', 8: 'JJA',
    9: 'SON', 10: 'SON', 11: 'SON',
    12: 'DJF'
}
grp_ary = [month_to_season_dct.get(t_stamp.month) for t_stamp in df.index]

with the following, which uses a numpy array as a lookup table.

month_to_season_lu = np.array([
    None,
    'DJF', 'DJF',
    'MAM', 'MAM', 'MAM',
    'JJA', 'JJA', 'JJA',
    'SON', 'SON', 'SON',
    'DJF'
])
grp_ary = month_to_season_lu[df.index.month]

Here's a timeit comparison of the two approaches on ~3 years of minutely data:

In [16]: timeit [month_to_season_dct.get(t_stamp.month) for t_stamp in df.index]
1 loops, best of 3: 12.3 s per loop

In [17]: timeit month_to_season_lu[df.index.month]
1 loops, best of 3: 549 ms per loop
like image 77
Garrett Avatar answered Oct 29 '25 04:10

Garrett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!