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': np.float64(6.75), 'y': np.float64(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 = {
...     "data": tsg,
...     "features": feature,
...     "bins": 2,
... }
>>> ep.groupby_apply("l2", nap.compute_tuning_curves, input_key="epochs", **func_kwargs)
{'x': <xarray.DataArray (unit: 3, 0: 2)> Size: 48B
array([[       nan, 1.        ],
       [       nan, 1.77777778],
       [       nan, 4.11111111]])
Coordinates:
  * unit     (unit) int64 24B 1 2 3
  * 0        (0) float64 16B -0.25 0.25
.. attribute:: occupancy

[nan 9.]

bin_edges#

[array([-0.5, 0. , 0.5])], ‘y’: <xarray.DataArray (unit: 3, 0: 2)> Size: 48B

array([[ nan, 1. ],

[ nan, 1.92857143], [ nan, 4.71428571]])

Coordinates:
  • unit (unit) int64 24B 1 2 3

  • 0 (0) float64 16B 0.75 1.25

pynapple.occupancy#

[nan 14.]

pynapple.bin_edges#

[array([0.5, 1. , 1.5])]}