Curious Minds

Clear answers to science and history questions

How NumPy Sum With Axis Works

· 6 min read · Science

NumPy's sum with an axis argument adds up array elements along a chosen dimension: the axis you specify is the one that gets collapsed, and the result has one fewer dimension than the input (for a 2D array, summing along axis 0 adds down the columns, producing a 1D array of column sums; summing along axis 1 adds across the rows, producing row sums). The key mental model is that axis names the dimension being reduced, not the direction of the addition.

Background: What an Axis Actually Is

In NumPy, an array is a grid of values with a shape, and each dimension of that shape is called an axis. A 1D array of length n has one axis (axis 0). A 2D array with shape (rows, columns) has two axes: axis 0 runs vertically down the rows, and axis 1 runs horizontally across the columns. Higher-dimensional arrays simply add more axes: a 3D array of shape (a, b, c) has axes 0, 1 and 2.

When you call np.sum(arr) without an axis, NumPy flattens the whole array and returns a single scalar. When you pass axis=0, you tell NumPy to reduce along the first dimension. The result keeps all the other dimensions intact. This is why the output shape is the input shape with the chosen axis removed.

It helps to think of the axis number as an index into the shape tuple. For a shape (3, 4), axis 0 has length 3 and axis 1 has length 4. Summing along axis 0 means you are adding the 3 values that share each column index, so the result has shape (4,). Summing along axis 1 means you are adding the 4 values that share each row index, so the result has shape (3,).

How It Works: Step by Step

To see the mechanics clearly, consider a small 2D array:

import numpy as np
arr = np.array([[1, 2, 3],
                [4, 5, 6]])

This array has shape (2, 3): two rows and three columns. Now apply sum with different axes:

  • np.sum(arr) returns 21 — the total of all six values.
  • np.sum(arr, axis=0) returns array([5, 7, 9]) — it adds down each column: 1+4, 2+5, 3+6.
  • np.sum(arr, axis=1) returns array([6, 15]) — it adds across each row: 1+2+3 and 4+5+6.

The process NumPy follows is consistent:

  1. Identify the axis to reduce from the axis argument.
  2. For every combination of indices on the remaining axes, gather the values along the chosen axis.
  3. Add those values together and place the result at the corresponding position in the output array.
  4. The output shape equals the input shape with the reduced axis removed.

For a 3D array of shape (2, 3, 4), summing along axis 1 produces shape (2, 4). Summing along axis 0 produces shape (3, 4). Summing along axis 2 produces shape (2, 3). You can also pass a tuple of axes, such as axis=(0, 2), to reduce multiple dimensions at once; the result then has the dimensions that were not reduced.

How to Choose the Right Axis

Choosing the correct axis is the most common source of confusion. A few practical rules help:

  • If you want a result per column in a 2D table, use axis=0. The column index survives, so the output length equals the number of columns.
  • If you want a result per row, use axis=1. The row index survives, so the output length equals the number of rows.
  • For images stored as (height, width, channels), summing along axis=2 collapses the colour channels and leaves a (height, width) array.
  • When unsure, check arr.shape and ask which dimension you want to disappear. That dimension's position in the shape tuple is the axis number.

Another way to phrase it: axis is the dimension you are summing over, not the dimension you are summing into. Many people initially expect axis=0 to produce row sums because they think of rows as the first thing they see, but the reduction removes the row dimension, leaving column totals.

Common Problems and Misconceptions

Several issues come up repeatedly when using sum with an axis:

  • Confusing axis with direction. The axis number refers to a position in the shape tuple, not to “horizontal” or “vertical.” For arrays with more than two dimensions, spatial intuition breaks down quickly.
  • Forgetting the output shape. Summing a 2D array along one axis returns a 1D array, not a scalar. If you need to keep the reduced dimension as length 1, use keepdims=True, which makes broadcasting easier later.
  • Negative axis values. NumPy accepts negative axes, counting from the end. For a 2D array, axis=-1 is the same as axis=1, and axis=-2 is the same as axis=0.
  • Data type overflow. Integer arrays are summed in their existing dtype by default, so summing many large integers can overflow silently. Passing dtype=np.int64 or a float type avoids surprises.
  • NaN propagation. If any value along the reduced axis is NaN, the result for that slice is NaN. Use np.nansum to treat NaNs as zero.

A frequent misconception is that axis=0 always means “sum the rows.” In a 2D array, axis=0 actually sums down the rows, producing one value per column. The row dimension is the one being consumed.

Comparing sum, nansum, and Other Reductions

NumPy provides several related functions that accept the same axis argument and follow the same shape rules:

  • np.sum — standard addition, propagating NaN.
  • np.nansum — treats NaN as zero.
  • np.mean, np.std, np.min, np.max — other reductions that collapse the chosen axis in exactly the same way.
  • arr.sum(axis=...) — the array method, equivalent to np.sum(arr, axis=...).

Because the axis semantics are shared across these functions, learning how sum handles axes transfers directly to computing means, standard deviations, minima and maxima along a dimension. The keepdims=True option is also available on all of them.

For performance, np.sum is implemented in compiled code and is generally much faster than a Python loop over the same values. The axis argument does not change the underlying algorithm; it only changes which dimension is traversed and reduced.

Frequently Asked Questions

What does axis=0 mean in numpy.sum?

It means reduce along the first dimension of the array. For a 2D array of shape (rows, columns), summing along axis 0 adds the values down each column, returning an array of length equal to the number of columns.

Why does summing a 2D array along axis=1 give row sums?

Axis 1 is the column dimension. Reducing it removes the columns and leaves one value per row, which is the sum of each row.

How do I keep the reduced dimension in the result?

Pass keepdims=True. For example, np.sum(arr, axis=0, keepdims=True) on a (2, 3) array returns shape (1, 3) instead of (3,). This is useful for broadcasting the result back against the original array.

Can I sum along more than one axis at once?

Yes. Pass a tuple, such as axis=(0, 1), to reduce both dimensions and return a scalar, or axis=(0, 2) on a 3D array to reduce the first and third dimensions while keeping the second.

What happens if I use a negative axis?

Negative axes count from the last dimension. For a 2D array, axis=-1 equals axis=1, and axis=-2 equals axis=0. This is convenient when you want the last axis regardless of how many dimensions the array has.

Does numpy.sum with axis change the data type?

By default, integer arrays are summed using the same integer dtype, which can overflow. You can pass dtype to control the accumulator type, for example dtype=np.float64 or dtype=np.int64.

In this article
  1. Background: What an Axis Actually Is
  2. How It Works: Step by Step
  3. How to Choose the Right Axis
  4. Common Problems and Misconceptions
  5. Comparing sum, nansum, and Other Reductions
  6. Frequently Asked Questions