Written and maintained by CASRAI Editorial Board
Last updated
Short answer: np.sum(a) adds every element of the array a and returns one number; np.sum(a, axis=0) adds down the columns of a 2-D array and np.sum(a, axis=1) adds across the rows. The point to check before you trust a total is what happens when a value is missing: np.sum propagates nan, so one missing measurement turns the whole total (or the whole row or column it sits in) into nan. This guide covers the arguments, a worked example with a missing value, the integer and float accumulator rules, and the errors you are most likely to hit. Outputs below were run on NumPy 2.5.1 on 2026-11-07, and the argument descriptions come from the NumPy 2.5 manual.
What np.sum is used for in research
Researchers reach for np.sum whenever data sit in an array and a total is needed: counts per sample, counts per time point, a total across an entire plate or grid, or the denominator for turning counts into proportions. The function reduces an array along the axes you name and returns an array with those axes removed, or a scalar when every axis is reduced. Typical uses in a research script:
- Row totals before dividing each row by its own total (see the
keepdimsstep below). - Column totals to compare conditions or time points.
- Totals that ignore missing observations, using
np.nansumor thewhereargument.
For spread rather than totals, see NumPy std: np.std syntax and ddof. The np.mean function is listed under “See also” in the official numpy.sum page.
Install or access (official source only)
The NumPy install page (numpy.org/install, checked 2026-11-07) says the only prerequisite for installing NumPy is Python itself, and suggests the Anaconda Distribution as the simplest way to get Python with NumPy. The commands listed there are:
pip install numpy(environment-based, with pip)conda install numpy(environment-based, with conda)uv pip install numpyorpixi add numpy(project-based)
Its tip for pip users is to work inside a virtual environment. To confirm the install, run the check the install page gives:
import numpy as np
print(np.__version__)
If you do not have Python yet, the CASRAI walkthrough Install Anaconda Python covers Windows, macOS and Linux.
Step-by-step: sum an array by axis, with a missing value
The counts below are illustrative values made up for this page, not measured data. They stand for 3 samples (rows) measured at 4 time points (columns), with one measurement missing for sample 2 at the third time point, stored as np.nan.
- Import NumPy and build the array.
import numpy as np counts = np.array([[12, 15, 14, 18], [10, 11, np.nan, 16], [9, 13, 12, 14]])The
np.nanforces the array to a float dtype, so every value prints with a decimal point. - Sum everything. With the default
axis=None, all elements are summed and a scalar is returned:np.sum(counts) # np.float64(nan)The one missing value makes the total
nan. Thenumpy.nansumpage describesnumpy.sumas “Sum across array propagating NaNs”. - Sum down the columns (axis=0). One total per time point:
np.sum(counts, axis=0) # array([31., 39., nan, 48.])Only the third column, which holds the missing value, is
nan. - Sum across the rows (axis=1). One total per sample:
np.sum(counts, axis=1) # array([59., nan, 48.])Only the second row is
nan. - Ignore the missing value with np.nansum. The NumPy docs describe
np.nansumas returning the sum “treating Not a Numbers (NaNs) as zero”:np.nansum(counts) # np.float64(144.0) np.nansum(counts, axis=0) # array([31., 39., 26., 48.]) np.nansum(counts, axis=1) # array([59., 37., 48.]) - Or keep np.sum and choose the elements with where. The
whereargument takes a boolean array of the elements to include:np.sum(counts, axis=1, where=~np.isnan(counts)) # array([59., 37., 48.])This gave the same row totals as
np.nansumhere. See NumPy NaN: how to detect, ignore and replace np.nan for the detection and replacement options. - Turn counts into row proportions with keepdims. With
keepdims=Truethe reduced axis stays as a size-one dimension, so the result broadcasts against the original array:row_totals = np.nansum(counts, axis=1, keepdims=True) # shape (3, 1) np.round(counts / row_totals, 3)Output:
array([[0.203, 0.254, 0.237, 0.305], [0.27 , 0.297, nan, 0.432], [0.188, 0.271, 0.25 , 0.292]])Each row now sums to 1 over its observed values; the missing cell stays
nanrather than being invented. The division relies on broadcasting, explained in Broadcasting in NumPy.
Arguments of numpy.sum
From the NumPy 2.5 manual page for numpy.sum (checked 2026-11-07). The signature is numpy.sum(a, axis=None, dtype=None, out=None, keepdims, initial, where), where keepdims, initial and where are left unset unless you pass them.
| Argument | What the manual says it does |
|---|---|
a |
Array-like of elements to sum. |
axis |
None, an int or a tuple of ints. The default axis=None sums all elements. A negative axis counts from the last axis to the first. A tuple sums over all the listed axes. |
dtype |
Type of the returned array and of the accumulator. The dtype of a is used unless a has an integer dtype with less precision than the default platform integer, in which case a platform integer is used. |
out |
Alternative output array, with the same shape as the expected output. |
keepdims |
If True, reduced axes are left in the result as dimensions of size one, so the result broadcasts against the input. |
initial |
Starting value for the sum. |
where |
Boolean array-like of the elements to include in the sum. |
Summing two arrays element-wise
People searching “numpy sum two arrays” or “numpy sum arrays element wise” usually want the element-wise sum, which is addition, not np.sum. The numpy.add page says it adds arguments element-wise and is “Equivalent to x1 + x2 in terms of array broadcasting”.
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[10, 20, 30], [40, 50, 60]])
a + b # array([[11, 22, 33], [44, 55, 66]])
np.add(a, b) # same result
np.sum([a, b], axis=0) # same result: stacks a and b, then sums over the stack axis
np.sum(a + b) # np.int64(231), the same as np.sum(a) + np.sum(b)
For element-wise multiplication, see Element-Wise Multiplication in NumPy.
Output and how to read it
| Call on the 3 × 4 array | What is reduced | Result shape |
|---|---|---|
np.sum(counts) |
All elements (axis=None) |
Scalar |
np.sum(counts, axis=0) |
Rows are collapsed: one value per column | (4,) |
np.sum(counts, axis=1) |
Columns are collapsed: one value per row | (3,) |
np.nansum(counts, axis=1, keepdims=True) |
Columns collapsed, axis kept with size one | (3, 1) |
The manual states that the result is “an array with the same shape as a, with the specified axis removed”, and a scalar if a is 0-d or axis is None. The shapes in the table come from running the calls above. axis=-1 counts from the last axis, so on this 2-D array it is the same as axis=1; np.nansum(counts, axis=-1) returned array([59., 37., 48.]).
Integer overflow and float precision
- Integer overflow is silent. The manual notes that arithmetic is modular for integer types and no error is raised on overflow. Its example:
np.ones(128, dtype=np.int8).sum(dtype=np.int8)returnsnp.int8(-128). Without thedtypeargument, the same sum on NumPy 2.5.1 returnednp.int64(128), because small integer inputs are accumulated in a platform integer. - Float summation is not exact. The manual explains that NumPy uses partial pairwise summation, always when no axis is given and, with an axis, only when summing along the fast axis in memory. For large arrays of low-precision floats such as float32 it says errors can become significant and that it can be advisable to pass
dtype=np.float64. Python’smath.fsumis slower but more precise. - An empty array sums to 0.
np.sum([])returns0.0.
Troubleshooting
| Symptom | Cause and fix |
|---|---|
The total, row or column is nan |
The data contain a nan and np.sum propagates it. Use np.nansum, or np.sum(..., where=~np.isnan(a)). Decide first whether dropping the value is appropriate for your analysis. |
TypeError: only integer scalar arrays can be converted to a scalar index from np.sum(a, b) |
The second positional argument of np.sum is axis, not a second array, so passing b there fails (message as raised on NumPy 2.5.1). To add two arrays use a + b or np.add(a, b), then call np.sum on the result if you want a total. |
AxisError: axis 2 is out of bounds for array of dimension 2 |
The axis number is larger than the array’s number of dimensions allows. For a 2-D array use axis 0 or 1 (or -1, -2). |
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape... from np.sum([[1, 2], [3]]) |
NumPy cannot build a regular array from rows of different lengths. Make the rows the same length, pad them deliberately, or sum each list separately. |
TypeError: the resolved dtypes are not compatible with add.reduce |
Raised when summing an array of strings (for example np.array(['1', '2'])). Convert to numbers first, for example with .astype(float). |
| Totals look wrong for small integer types | An accumulator that is too small wraps around without warning. Pass a wider dtype, such as dtype=np.int64. |
| The result has fewer dimensions than the input and will not broadcast | Pass keepdims=True to keep the reduced axis with size one. |
Error messages are quoted as raised on NumPy 2.5.1 (run 2026-11-07) and may be worded differently in other NumPy versions.
Free alternatives
Several free tools can add numbers. They differ in how they treat NaN and what shape they return.
| Tool | What the official documentation says | Behaviour on the example above |
|---|---|---|
ndarray.sum method (counts.sum(axis=0)) |
Listed in the numpy.sum page as the equivalent method. |
Same results as np.sum; a.sum(axis=0) gave array([5, 7, 9]) for the 2 × 3 array a. |
Python built-in sum() |
“Sums start and the items of an iterable from left to right and returns the total.” Python’s docs point to math.fsum() for extended-precision float addition. |
On a 2-D array the items are the rows, so sum(a) returned array([5, 7, 9]) (the column sums), not a single total. |
math.fsum |
“Return an accurate floating-point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums.” | For plain iterables of numbers; it takes no axis argument. |
pandas DataFrame.sum |
Signature DataFrame.sum(*, axis=0, skipna=True, numeric_only=False, min_count=0, **kwargs). skipna=True excludes NA values, and the sum of an empty or all-NA series is 0 unless min_count is set. |
On a DataFrame built from counts (pandas 3.0.5), df.sum() returned 31.0, 39.0, 26.0 and 48.0 for the four columns, with no nan; df.sum(skipna=False) returned nan for the third column. |
To build such a DataFrame from an array, see Create a DataFrame in Python.
FAQ
What is the difference between np.sum axis=0 and axis=1?
On a 2-D array, axis=0 collapses the rows and returns one total per column; axis=1 collapses the columns and returns one total per row. In the example above, axis=0 returned four values and axis=1 returned three, for a 3 × 4 array.
How do I sum two numpy arrays?
Add them with a + b or np.add(a, b), which works element-wise when the shapes match or can be broadcast. Passing the second array to np.sum as in np.sum(a, b) fails, because the second positional argument is axis.
Why does np.sum return nan?
At least one element is nan, and np.sum propagates it. Use np.nansum or the where argument to leave missing values out.
How do I use np.sum in Python with a plain list?
The first argument is array-like, so a list of numbers works: the NumPy manual’s own example, np.sum([0.5, 1.5]), returns 2.0, and a nested list such as [[0, 1], [0, 5]] returns 6.
Sources (official docs)
Sources checked on 2026-11-07. Outputs not quoted from these pages were produced by running the code on NumPy 2.5.1 and pandas 3.0.5.
- NumPy manual, numpy.sum (v2.5): signature, arguments, return shape, overflow and precision notes.
- NumPy manual, numpy.nansum: NaNs treated as zero; see-also note that
numpy.sumpropagates NaNs. - NumPy manual, numpy.add: element-wise addition and its equivalence to
x1 + x2. - NumPy, Installing NumPy: installation commands and version check.
- pandas documentation, DataFrame.sum: signature and
skipna/min_countbehaviour. - Python documentation, built-in sum() and math.fsum().







