Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy cumsum: Cumulative Sums in Python Guide

A research guide to numpy cumsum in Python: calculate cumulative totals across axes, handle integer overflow, avoid NaN drift, and optimize array memory.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In quantitative research and scientific computing, computing running totals across sequential observations is a standard analytical task. The numpy.cumsum function in Python provides vectorized cumulative summation across multi-dimensional arrays, enabling researchers to track cumulative experimental quantities, evaluate empirical distribution functions, and aggregate time-series data without writing slow iterative loops.

What it is used for in research

In laboratory and data-intensive research workflows, cumulative sums serve several foundational analytical functions:

  • Empirical Cumulative Distribution Functions (eCDFs): Calculating cumulative probabilities and cumulative frequency distributions to compare observed experimental distributions against theoretical models, such as in an ogive (cumulative frequency polygon).
  • Quality Control and Pareto Analysis: Evaluating cumulative defect percentages or experimental failure modes in laboratory quality assurance, directly supporting Pareto chart generation.
  • Longitudinal Observation and Dose-Response Tracking: Accumulating daily environmental measurements, continuous clinical biomarker exposures, or cumulative photon counts in physical spectroscopy.
  • Stochastic Modeling and Random Walks: Simulating Brownian motion and Markov chain Monte Carlo (MCMC) trajectories by taking the cumulative sum of independent, identically distributed random step increments.
  • Open Science and Computational Reproducibility: Implementing high-performance array transformations in research software published in outlets such as the Journal of Open Source Software (JOSS) following established FAIR data principles.

How to install or access it

NumPy is distributed through standard, authenticated package repositories. The official installation routes documented by the NumPy project and the Python Software Foundation are as follows:

Standard Installation via pip

pip install numpy

Scientific Environment Installation via Conda

conda install -c conda-forge numpy

Isolated Virtual Environment Setup

For reproducible scientific computing, maintain isolated package environments to prevent version conflicts across analytical pipelines:

python -m venv .venv
source .venv/bin/activate  # On Windows: .venvScriptsactivate
pip install --upgrade pip
pip install numpy

Modern NumPy 2.x releases require Python 3.10 or higher. Verify installation and check the active library version in your Python interpreter:

import numpy as np
print(np.__version__)

Step-by-step instructions

The standard syntax defined in the official NumPy reference manual is:

numpy.cumsum(a, axis=None, dtype=None, out=None)

Follow these numbered steps to calculate cumulative sums across 1D and multi-dimensional research datasets:

1. Import NumPy and Initialize the Research Array

Define an array representing sequential observations, specifying an appropriate integer or floating-point precision:

import numpy as np

# Daily experimental participant enrollments across 6 study days
daily_enrollments = np.array([12, 18, 25, 14, 31, 22], dtype=np.int64)

2. Compute a One-Dimensional Cumulative Sum

Call np.cumsum() on the 1D array to compute running totals across the full sequence:

cumulative_enrollments = np.cumsum(daily_enrollments)
print("Daily:     ", daily_enrollments)
print("Cumulative:", cumulative_enrollments)
# Output: [ 12  30  55  69 100 122]

3. Compute Cumulative Sums Across Multi-Dimensional Axes

When analyzing multi-cohort or multi-channel experimental data organized in a 2D matrix, specify the axis parameter to control the direction of accumulation:

# Matrix representing 3 experimental cohorts (rows) across 4 measurement intervals (columns)
cohort_data = np.array([
    [10, 15, 20, 25],
    [8,  12, 19, 22],
    [14, 18, 21, 26]
])

# Sum down columns (axis=0): running total across cohorts for each time interval
time_cumsum = np.cumsum(cohort_data, axis=0)

# Sum across rows (axis=1): running total across time intervals for each cohort
cohort_cumsum = np.cumsum(cohort_data, axis=1)

If axis=None (the default), NumPy flattens the multi-dimensional array into a 1D sequence before accumulating.

4. Execute In-Place Computations for Large Datasets

To avoid duplicating memory allocations when processing gigabyte-scale datasets, pass a pre-allocated array of matching shape and type to the out parameter:

# Allocate destination buffer
out_buffer = np.empty_like(cohort_data)

# Compute cumulative sum directly into out_buffer
np.cumsum(cohort_data, axis=1, out=out_buffer)

Output and how to read it

The output of numpy.cumsum is an ndarray containing the sequential partial sums:

  • 1D Array Output: The result matches the exact shape and size of the input. For the input vector [12, 18, 25, 14, 31, 22], the output array is [12, 30, 55, 69, 100, 122]:
    • Index 0: 12 (first observation)
    • Index 1: 12 + 18 = 30
    • Index 2: 30 + 25 = 55
    • Index 3: 55 + 14 = 69
    • Index 4: 69 + 31 = 100
    • Index 5: 100 + 22 = 122 (total sum across all observations)
  • Multi-Dimensional Output: When axis=0 is chosen on an M × N matrix, the resulting array has shape M × N, where row i contains the sum of all rows from 0 to i for each column. When axis=1 is selected, column j contains the sum of all columns from 0 to j for each row.
  • Flattened Output: When axis=None, the output is a 1D vector of length M × N representing the raster-scan cumulative total.

Researchers transitioning from R will note that base R’s cumsum() is restricted to 1D vectors and requires wrapper loops or apply() for matrices, as outlined in our guide on summation in R.

Troubleshooting

When applying numpy.cumsum to experimental datasets, four common numerical and operational issues can occur:

1. Silent Modular Integer Overflow

Symptom: Cumulative totals suddenly turn into unexpected negative numbers or decrease without warning.
Cause: In NumPy, integer arithmetic is modular. When an accumulator reaches the upper limit of its integer bit-width (such as 127 for int8, 32,767 for int16, or 2,147,483,647 for int32), it wraps around to negative values. NumPy does not raise an OverflowError or runtime warning on integer overflow.
Solution: Explicitly pass dtype=np.int64 or dtype=float to enlarge the accumulator bit-width:

# Prevents 32-bit overflow on large research counts
safe_cumsum = np.cumsum(large_counts, dtype=np.int64)

2. Missing Values (NaN) Propagating Across All Downstream Steps

Symptom: After an unobserved data point or sensor dropout, every subsequent cumulative value becomes nan.
Cause: By mathematical definition in IEEE 754 floating-point arithmetic, any addition involving NaN yields NaN. Standard np.cumsum propagates this through all remaining indices.
Solution: Use numpy.nancumsum, which treats NaN as zero during summation, or apply NumPy masked arrays:

experimental_readings = np.array([4.2, 5.1, np.nan, 3.8, 6.0])

# np.cumsum returns: [4.2, 9.3, nan, nan, nan]
# np.nancumsum returns: [4.2, 9.3, 9.3, 13.1, 19.1]
clean_totals = np.nancumsum(experimental_readings)

3. Floating-Point Accumulation Discrepancy (cumsum vs. sum)

Symptom: The final element np.cumsum(x)[-1] does not exactly equal np.sum(x).
Cause: np.sum uses a pairwise summation algorithm that recursively splits arrays into smaller blocks, substantially reducing cumulative rounding errors. In contrast, np.cumsum uses sequential accumulation, which is subject to continuous roundoff accumulation drift.
Solution: Avoid strict equality checks (==) when validating cumulative totals against array sums. Use np.isclose() with appropriate relative tolerance:

assert np.isclose(np.cumsum(x)[-1], np.sum(x), rtol=1e-12)

4. Buffer Shape Mismatch on the out Parameter

Symptom: ValueError: output array is not acceptable (must have the same size and shape).
Cause: The array passed to out has a different shape or memory size than the expected result.
Solution: Pre-allocate the output buffer with np.empty_like(a) or ensure matching dimensions before calling np.cumsum.

Free alternatives

Depending on data scale, programming environment, and pipeline architecture, several free and open-source alternatives offer cumulative summation capabilities:

Software / Function Language / Environment Axis Support NaN Handling Key Analytical Distinction
numpy.cumsum Python (NumPy) Arbitrary N-D axes (0, 1, …) Propagates NaNs (use nancumsum to bypass) Vectorized C implementation; supports in-place buffer assignment via out.
itertools.accumulate Python Standard Library 1D iterables only Propagates NaNs Generator-based lazy evaluation; zero external dependencies; minimal memory overhead for streaming single-pass files.
pandas.Series.cumsum Python (Pandas) Index and columns Skips NaNs by default (skipna=True) Preserves DataFrame labels, time-series DatetimeIndex stamps, and categorical groupings.
base::cumsum R 1D vectors only Propagates NAs Built directly into standard R distribution; multi-dimensional use requires apply() wrappers.
Base.cumsum Julia Arbitrary dimensions (dims) Propagates NaNs Native just-in-time compilation; zero-cost array slicing and views.
torch.cumsum Python (PyTorch) Specified dimension (dim) Propagates NaNs GPU hardware acceleration and autograd automatic differentiation for deep learning research.

FAQ

How does axis work in numpy cumsum?

The axis parameter designates the dimension along which cumulative accumulation occurs. In a 2D matrix, axis=0 calculates cumulative totals downward across rows (resulting in running totals for each column). Setting axis=1 calculates cumulative totals across columns (yielding running totals for each row). When axis=None is specified, the input array is flattened into a 1D array before cumulative summation.

What is the difference between numpy cumsum and nancumsum?

Standard numpy.cumsum propagates NaN values, causing all array positions downstream of a NaN to evaluate to NaN. In contrast, numpy.nancumsum treats NaN values as numeric zeros during summation, maintaining uninterrupted cumulative totals across time-series data with missing observations.

Why does numpy cumsum give negative numbers with integers?

NumPy performs modular arithmetic for integer dtypes and does not throw an exception when an accumulator exceeds its maximum bit-width capacity. If an accumulator overflows 32-bit integer limits (approx. 2.14 billion), it wraps around to negative values. To prevent silent data corruption, set dtype=np.int64 or convert the array to floating-point representation.

Why is the last element of cumsum not equal to sum?

In floating-point arithmetic, np.sum utilizes pairwise summation, recursively dividing the array into sub-blocks to minimize cumulative rounding errors. numpy.cumsum executes sequential left-to-right additions, accumulating numerical roundoff drift along the sequence. For floating-point arrays, compare the final cumulative value to the sum using np.isclose() rather than exact equality.

Can numpy cumsum be performed in place to save memory?

Yes. By specifying the out parameter with an existing array of identical shape and data type (such as np.cumsum(arr, out=arr)), NumPy writes cumulative totals directly into the provided memory buffer, eliminating the memory overhead of allocating a new array.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about NumPy cumsum: Cumulative Sums in Python Guide

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →