I have a grouped DataFrame that I want to combine with a dictionary of functions that should appear in specific columns. It is easy for single-level columns: groups.agg({'colname': <function>}). However, I am struggling for this to work with multi-level columns, of which I only want to reference one level.
Here is an example.
Allows you to make some sample data:
import itertools
import pandas as pd
lev1 = ['foo', 'bar', 'baz']
lev2 = list('abc')
n = 6
df = pd.DataFrame({k: np.random.randn(n) for k in itertools.product(lev1,lev2)},
index=pd.DatetimeIndex(start='2015-01-01', periods=n, freq='11D'))
It looks like this:
bar baz foo
a b c a b c a b c
2015-01-01 -1.11 2.12 -1.00 0.18 0.14 1.24 0.73 0.06 3.66
2015-01-12 -1.43 0.75 0.38 0.04 -0.33 -0.42 1.00 -1.63 -1.35
2015-01-23 0.01 -1.70 -1.39 0.59 -1.10 -1.17 -1.51 -0.54 -1.11
2015-02-03 0.93 0.70 -0.12 1.07 -0.97 -0.45 -0.19 0.11 -0.79
2015-02-14 0.30 0.49 0.60 -0.28 -0.38 1.11 0.15 0.78 -0.58
2015-02-25 -0.26 0.51 0.82 0.05 -1.45 0.14 0.53 -0.33 -1.35
And grouping by month:
groups = df.groupby(pd.TimeGrouper('MS'))
Define some functions based on the top level in columns:
funcs = {'bar': np.sum, 'baz': np.mean, 'foo': np.min}
However, execution groups.agg(funcs)results in a KeyError as it expects a key for each level, which makes sense.
This works for example:
groups.agg({('bar', 'a'): np.mean})
bar
a
2015-01-01 -0.845554
2015-02-01 0.324897
But I do not want to indicate each key in the second level. Therefore, I am looking for something that will work as follows:
groups.agg({('bar', slice(None)): np.mean})
, slice .
:
def multifunc(group):
func = funcs[group.name[0]]
return func(group)
groups.agg(multifunc)
"". , agg. / , .