Tutorial

numpy.sum() in Python

Comprehensive numpy sum python guide: syntax, parameters (axis, dtype, out, keepdims, initial), and practical examples including axis use, keepdims, dtype, out, initial, and nansum.

Drake Nguyen

Founder · System Architect

3 min read
numpy.sum() in Python
numpy.sum() in Python

Overview

The numpy sum python function (np.sum) computes the sum of elements in an ndarray. It supports reduction over one or more axes, dtype casting, writing results to an existing array, preserving reduced dimensions, and an initial value. This makes it a flexible, vectorized alternative to the built-in python sum for numeric arrays.

Syntax and parameters

np.sum(a, axis=None, dtype=None, out=None, keepdims=False, initial=0)
  • a: input array whose elements are summed.
  • axis: None (flatten and sum all elements), an int (reduce that axis), or a tuple of ints (reduce multiple axes). See notes on np.sum axis 0 vs axis 1.
  • dtype: data-type for the returned sum. Use this to avoid overflow or to get a floating-point result (e.g., numpy sum dtype=float).
  • out: optional array to store the result (numpy sum out parameter example).
  • keepdims: if True, the reduced axes are retained with size 1 (numpy sum keepdims true). This makes broadcasting with the original array easier.
  • initial: starting value added to the sum (numpy sum initial parameter). Useful for empty arrays or custom offsets.

Examples

The examples below show common uses: summing all elements, reducing along axes, controlling dtype, using an initial value, keeping dimensions, and handling NaNs.

1. Sum of all elements (flattened)

import numpy as np

arr = np.array([[1, 2], [3, 4], [5, 6]])
total = np.sum(arr)
print('Sum of all elements:', total)
# Output: Sum of all elements: 21

2. Sum along axes (np.sum axis 0 vs axis 1)

import numpy as np

arr = np.array([[1, 2], [3, 4], [5, 6]])
col_sum = np.sum(arr, axis=0)   # sums each column
row_sum = np.sum(arr, axis=1)   # sums each row
print('Sum along axis 0 (columns):', col_sum)
print('Sum along axis 1 (rows):', row_sum)
# Output:
# Sum along axis 0 (columns): [ 9 12]
# Sum along axis 1 (rows): [ 3  7 11]

3. Specify output dtype (np.sum dtype parameter)

import numpy as np

arr = np.array([[1, 2], [3, 4]])
s = np.sum(arr, axis=1, dtype=float)
print('Row sums as float:', s)
# Output: Row sums as float: [3. 7.]

4. Using an initial value (numpy sum initial parameter)

import numpy as np

arr = np.array([[1, 2], [3, 4]])
with_initial = np.sum(arr, axis=1, initial=10)
print('Row sums with initial value 10:', with_initial)
# Output: Row sums with initial value 10: [13 17]

5. Keep reduced dimensions (numpy sum keepdims example)

import numpy as np

arr = np.arange(12).reshape(3,4)
# keepdims=True preserves the axis as size 1
s = np.sum(arr, axis=1, keepdims=True)
print('Shape with keepdims:', s.shape)
print('Value with keepdims:', s)
# Example output: Shape with keepdims: (3, 1)

6. Writing result into an existing array (out parameter)

import numpy as np

arr = np.array([1, 2, 3], dtype=int)
out = np.empty((), dtype=int)
np.sum(arr, out=out)
print('Result stored in out:', out)
# Output: Result stored in out: 6

7. Sum of empty array with initial and dtype

import numpy as np

empty = np.array([], dtype=int)
# initial ensures a defined result for empty arrays
res = np.sum(empty, initial=5, dtype=int)
print('Sum of empty array with initial 5:', res)
# Output: Sum of empty array with initial 5: 5

8. NaN-safe summation (numpy sum ignore nan - nansum)

import numpy as np

arr = np.array([1.0, np.nan, 3.0])
# np.nansum ignores NaNs when summing
safe = np.nansum(arr)
print('nansum result:', safe)
# Output: nansum result: 4.0

Note: np.sum performs vectorized aggregation that is usually faster and more flexible than python sum array numpy applied to lists. For edge cases (overflow, NaNs, preserving dims, or writing to an output buffer) prefer the appropriate numpy parameters or related functions like np.nansum.

For details on behavior across NumPy versions and full parameter descriptions, consult the official NumPy documentation.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.