fips.aggregate.sum#

fips.aggregate.sum(space, by, blocks=None, dropna=False)[source]#

Return the operator that sums the labels of space by group.

Parameters:
  • space (Space) – The labels to sum: the state’s or the observations’.

  • by (Any) – The groups: level names, a pandas.Grouper with a level and a freq, an pandas.IntervalIndex named after a level, or a pandas.Series that maps a level’s values to groups (see fips.aggregate). Every block summed must have the levels the keys read.

  • blocks (str | Sequence[str] | None) – The blocks to sum, each on its own; every block by default. A block not named is passed through, one row for each of its labels (left out with dropna).

  • dropna (bool) – Leave out the labels a key cannot place (outside every interval, missing from a mapping, mapped to NaN) and the blocks not named in blocks, instead of raising and passing them through: their columns of \(W\) are zero. This picks part of the state, such as the cells of one region or the months of one year, as pandas’ groupby(dropna=True) leaves out a missing key.

Returns:

\(W\), sparse, with one row per group (ones where a label is in the group) and space as its columns. Its rows are a space of the same blocks, each labeled by its groups in sorted order on the levels the keys name (a block passed through keeps its labels; a block dropna leaves out entirely is not there).

Return type:

Operator

Raises:
  • TypeError – If space is not a Space, or a key is of another kind.

  • ValueError – If by is empty, a block summed lacks a level a key reads, a key cannot place a label (outside every interval, missing from a mapping or mapped to NaN) without dropna, dropna leaves out every label, two keys label one level, or blocks names no block of space.

See also

mean

The operator that averages by group.

fips.Posterior.cov

The posterior covariance of aggregates of the state.

fips.Problem.aggregate

The problem of aggregated observations.

Examples

>>> import numpy as np
>>> import pandas as pd
>>> import fips
>>> cells = pd.MultiIndex.from_product(
...     [pd.date_range("2020-01-01", periods=2, freq="MS"), ["a", "b", "c"]],
...     names=["time", "cell"],
... )
>>> flux = fips.Vector.from_series(
...     pd.Series(np.arange(6.0), index=cells), block="flux"
... )
>>> W = fips.aggregate.sum(flux.space, by="time")
>>> W.rows
Space(flux: 2 x ['time'])
>>> (W @ flux).values
array([ 3., 12.])

The total of a region in each month: a Series maps the region’s cells, and dropna leaves out the others:

>>> region = pd.Series(
...     "north", index=pd.Index(["a", "b"], name="cell"), name="region"
... )
>>> W = fips.aggregate.sum(flux.space, by=["time", region], dropna=True)
>>> W.rows.select("flux")
MultiIndex([('2020-01-01', 'north'),
            ('2020-02-01', 'north')],
           names=['time', 'region'])
>>> (W @ flux).values
array([1., 7.])