Numbagg: Fast N-dimensional aggregation functions with Numba
Fast, flexible N-dimensional array functions written with
Numba and NumPy's generalized
ufuncs.
Why use numbagg?
Performance
Outperforms pandas
On a single core, 2-10x faster for moving window functions, 1-2x faster for
aggregation and grouping functions
When parallelizing with multiple cores, 4-30x faster
Outperforms bottleneck on multiple cores
On a single core, matches bottleneck
When parallelizing with multiple cores, 3-7x faster
Outperforms numpy on multiple cores
On a single core, matches numpy
When parallelizing with multiple cores, 5-15x faster
...though numbagg's functions are JIT compiled, so the first run is much slower
Versatility
More functions (though bottleneck has some functions we don't have, and pandas' functions
have many more parameters)
Functions work for >3 dimensions with flexible axis handling (see Axis Parameter Behavior below)
Written in numba — way less code, simple to inspect, simple to improve
Functions & benchmarks
Summary benchmark
Two benchmarks summarize numbagg's performance — the first with a 1D array of 10M elements without
parallelization, and a second with a 2D array of 100x10K elements with parallelization1. Numbagg's relative
performance is much higher where parallelization is possible. A wider range of arrays is
listed in the full set of benchmarks below.
The values in the table are numbagg's performance as a multiple of other libraries for a
given shaped array calculated over the final axis. (so 1.00x means numbagg is equal,
higher means numbagg is faster.)
# Example with 3D array
arr = np.random.rand(4, 3, 5)
result = nb.nanmean(arr, axis=(0, 2)) # Reduces over dimensions 0 and 2
# result.shape is (3,)
Moving window functions
Includes: move_mean, move_sum, move_std, move_var, move_corr, move_cov, and exponential variants like move_exp_nanmean
Specify the dimension along which the window moves
Single axis only
Preserve input shape
# Moving average along axis 1
arr = np.random.rand(4, 3, 5)
result = nb.move_mean(arr, window=2, axis=1)
# result.shape is (4, 3, 5) - same as input
Grouped functions
Includes: group_nanmean, group_nansum, group_nanstd, group_nanvar, group_nanmin, group_nanmax, and others
Specify the dimensions along which groups are defined
Support multiple axes, e.g. axis=(1, 2), with a labels array whose shape matches those axes
Gather every position sharing a label into one group, whether or not those positions are adjacent
Remove the grouped dimensions and append a group dimension to the end of the output shape
# Group operations along axis 0
arr = np.random.rand(4, 3, 5)
labels = np.array([0, 1, 0, 1]) # Groups for axis 0; equal labels needn't be adjacent
result = nb.group_nanmean(arr, labels, axis=0)
# result.shape is (3, 5, 2) - axis 0 is dropped, and the 2 groups are appended
Aggregation functions are compatible with NumPy's axis parameter behavior, while moving window and grouped functions provide functionality not available in NumPy.
Matrix functions
Includes: nancorrmatrix, nancovmatrix (static), and move_corrmatrix, move_covmatrix, move_exp_nancorrmatrix, move_exp_nancovmatrix (moving)
Matrix functions use different dimension conventions:
The different conventions follow a simple principle: dimensions should only be added or removed at the end of the array shape. Static functions both remove (the obs dimension) and add (a second vars dimension), so they need obs at the end. Moving functions only add (a second vars dimension), so they can keep the natural time-series ordering with obs before vars.
Example implementation
Numbagg makes it easy to write, in pure Python/NumPy, flexible aggregation
functions accelerated by Numba. All the hard work is done by Numba's JIT
compiler and NumPy's gufunc machinery (as wrapped by Numba).
For example, here is how we wrote nansum:
import numpy as np
from numba import float32, float64, int32, int64
from numbagg.decorators import ndaggregate
@ndaggregate.wrap(
signature=[
(int32[:], int32[:]),
(int64[:], int64[:]),
(float32[:], float32[:]),
(float64[:], float64[:]),
]
)
def nansum(a, out):
asum = a.dtype.type(0)
for ai in a:
if not np.isnan(ai):
asum += ai
out[0] = asum
nansum(np.array([[1.0, 2.0, np.nan], [4.0, 5.0, 6.0]]), axis=-1) # array([3., 15.])
Implementation details
Numbagg includes somewhat awkward workarounds for features missing from
NumPy/Numba:
It implements its own cache for functions wrapped by Numba's
guvectorize, because that decorator is rather slow.
Already some of the ideas here have flowed upstream to numba (for example, an
axis parameter), and we hope
that others will follow.
License
3-clause BSD. Includes portions of Bottleneck, which is distributed under a
Simplified BSD license.
Footnotes
Matrix functions (correlation/covariance matrices) have no 1D benchmark — the
smallest input they accept is 2D — so their largest 2D shape appears in the
1D column. The 2D column has no entry for them, because no comparison library
accepts more than two dimensions. ↩↩2
This function is not currently parallelized, so exhibits worse performance
on parallelizable arrays. ↩↩2↩3↩4↩5↩6↩7↩8↩9
Benchmarks were run on a Mac M3 Max laptop in September 2024 on numbagg's HEAD,
pandas 2.2.2, bottleneck 1.4.0 numpy 2.0.1, with python numbagg/test/run_benchmarks.py -- --benchmark-max-time=10. They run in CI,
though GHA's low CPU count means we don't see the full benefits of
parallelization. ↩
While we separate the setup and the running of the functions, pandas still
needs to do some work to create its result dataframe, and numbagg does some
checks in python which bottleneck does in C or doesn't do. So use benchmarks
on larger arrays for our summary so we can focus on the computational speed,
which doesn't asymptote away. Any contributions to improve the benchmarks are
welcome. ↩
In some instances, a library won't have the exact function — for example,
pandas doesn't have an equivalent move_exp_nancount function, so we use
its sum function on an array of 1s. Similarly for
group_nansum_of_squares, we use two separate operations. ↩
anynan & allnan are also functions in numbagg, but not listed here as they
require a different benchmark setup. ↩
Alternatives
Use instead of numbagg: tools that do the same job, closest first.