pynapple.IntervalSet.groupby_apply#
- IntervalSet.groupby_apply(by, func, input_key=None, **func_kwargs)[source]#
Apply a function to each group in a grouped pynapple object.
- Parameters:
by (str or list of str) – Metadata name(s) to group by.
func (function) – Function to apply to each group.
input_key (str or None, optional) – Input key that the grouped object will be passed as. If None, the grouped object will be passed as the first positional argument.
**func_kwargs (optional) – Additional keyword arguments to pass to the function. Any required positional arguments that are not the grouped object should be passed as keyword arguments.
- Returns:
Dictionary of results from applying the function to each group, where the keys are the group names and the values are the results.
- Return type:
dict
Examples
>>> import pynapple as nap >>> import numpy as np >>> times = np.array([[0, 5], [10, 12], [20, 33]]) >>> metadata = {"l1": [1, 2, 2], "l2": ["x", "x", "y"]} >>> ep = nap.IntervalSet(times,metadata=metadata) >>> print(ep) index start end l1 l2 0 0 5 1 x 1 10 12 2 x 2 20 33 2 y shape: (3, 2), time unit: sec.
Apply a numpy function:
>>> ep.groupby_apply("l2", np.mean)
{‘x’: 6.75, ‘y’: 26.5}
Apply a custom function:
>>> ep.groupby_apply("l2", lambda x: x.shape[0]) {'x': 2, 'y': 1}
Apply a function with additional arguments:
>>> ep.groupby_apply("l2", np.mean, axis=1) {'x': array([ 2.5, 11. ]), 'y': array([26.5])}
Applying a function with additional arguments, where the grouped object is not the first argument:
>>> tsg = nap.TsGroup( ... { ... 1: nap.Ts(t=np.arange(0, 40)), ... 2: nap.Ts(t=np.arange(0, 40, 0.5), time_units="s"), ... 3: nap.Ts(t=np.arange(0, 40, 0.2), time_units="s"), ... }, ... ) >>> feature = nap.Tsd(t=np.arange(40), d=np.concatenate([np.zeros(20), np.ones(20)])) >>> func_kwargs = { >>> "group": tsg, >>> "feature": feature, >>> "nb_bins": 2, >>> } >>> ep.groupby_apply("l2", nap.compute_1d_tuning_curves, input_key="ep", **func_kwargs) {'x': 1 2 3 0.25 1.025641 1.823362 4.216524 0.75 NaN NaN NaN, 'y': 1 2 3 0.25 NaN NaN NaN 0.75 1.025641 1.978022 4.835165}