Consider a small 2d array:

In [180]: A=np.arange(12).reshape(3,4)
In [181]: A
Out[181]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Sum across rows; the result is a (3,) array

In [182]: A.sum(axis=1)
Out[182]: array([ 6, 22, 38])

But to sum (or divide) A by the sum requires reshaping

In [183]: A-A.sum(axis=1)
...
ValueError: operands could not be broadcast together with shapes (3,4) (3,) 
In [184]: A-A.sum(axis=1)[:,None]   # turn sum into (3,1)
Out[184]: 
array([[ -6,  -5,  -4,  -3],
       [-18, -17, -16, -15],
       [-30, -29, -28, -27]])

If I use keepdims, "the result will broadcast correctly against" A.

In [185]: A.sum(axis=1, keepdims=True)   # (3,1) array
Out[185]: 
array([[ 6],
       [22],
       [38]])
In [186]: A-A.sum(axis=1, keepdims=True)
Out[186]: 
array([[ -6,  -5,  -4,  -3],
       [-18, -17, -16, -15],
       [-30, -29, -28, -27]])

If I sum the other way, I don't need the keepdims. Broadcasting this sum is automatic: A.sum(axis=0)[None,:]. But there's no harm in using keepdims.

In [190]: A.sum(axis=0)
Out[190]: array([12, 15, 18, 21])    # (4,)
In [191]: A-A.sum(axis=0)
Out[191]: 
array([[-12, -14, -16, -18],
       [ -8, -10, -12, -14],
       [ -4,  -6,  -8, -10]])

If you prefer, these actions might make more sense with np.mean, normalizing the array over columns or rows. In any case it can simplify further math between the original array and the sum/mean.

Answer from hpaulj on Stack Overflow
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.mean.html
numpy.mean — NumPy v2.5 Manual
If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.
Top answer
1 of 4
46

Consider a small 2d array:

In [180]: A=np.arange(12).reshape(3,4)
In [181]: A
Out[181]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Sum across rows; the result is a (3,) array

In [182]: A.sum(axis=1)
Out[182]: array([ 6, 22, 38])

But to sum (or divide) A by the sum requires reshaping

In [183]: A-A.sum(axis=1)
...
ValueError: operands could not be broadcast together with shapes (3,4) (3,) 
In [184]: A-A.sum(axis=1)[:,None]   # turn sum into (3,1)
Out[184]: 
array([[ -6,  -5,  -4,  -3],
       [-18, -17, -16, -15],
       [-30, -29, -28, -27]])

If I use keepdims, "the result will broadcast correctly against" A.

In [185]: A.sum(axis=1, keepdims=True)   # (3,1) array
Out[185]: 
array([[ 6],
       [22],
       [38]])
In [186]: A-A.sum(axis=1, keepdims=True)
Out[186]: 
array([[ -6,  -5,  -4,  -3],
       [-18, -17, -16, -15],
       [-30, -29, -28, -27]])

If I sum the other way, I don't need the keepdims. Broadcasting this sum is automatic: A.sum(axis=0)[None,:]. But there's no harm in using keepdims.

In [190]: A.sum(axis=0)
Out[190]: array([12, 15, 18, 21])    # (4,)
In [191]: A-A.sum(axis=0)
Out[191]: 
array([[-12, -14, -16, -18],
       [ -8, -10, -12, -14],
       [ -4,  -6,  -8, -10]])

If you prefer, these actions might make more sense with np.mean, normalizing the array over columns or rows. In any case it can simplify further math between the original array and the sum/mean.

2 of 4
5

You can keep the dimension with "keepdims=True" if you sum a matrix For example:

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

np.sum(x, keepdims=True).shape
# (1, 1)
np.sum(x, keepdims=True)
# array([[21]]) <---the reault is still a 1x1 array

np.sum(x, keepdims=False).shape
# ()
np.sum(x, keepdims=False)
# 21 <--- the result is an integer with no dimesion
Discussions

np.mean with keepdims=True does not work on memmap
I'm using numpy 1.9.2 (built locally with pip and linked to openblas) and there seems to be a strange bug with memmap. I checked through recent issues/pr and nothing seemed reported (I don'... More on github.com
🌐 github.com
8
December 1, 2015
keepdims fails when taking mean
The keepdims argument is ignored ... Oddly, there's no documentation for pd.DataFrame.mean suggesting keepdims should even be allowed as an argument, but it accepts it with no effect. This also modifies the behavior of np.mean.... More on github.com
🌐 github.com
6
May 3, 2017
Top answer
1 of 2
102

@Ney @hpaulj is correct, you need to experiment, but I suspect you don't realize that summation for some arrays can occur along axes. Observe the following which reading the documentation

>>> a
array([[0, 0, 0],
       [0, 1, 0],
       [0, 2, 0],
       [1, 0, 0],
       [1, 1, 0]])
>>> np.sum(a, keepdims=True)
array([[6]])
>>> np.sum(a, keepdims=False)
6
>>> np.sum(a, axis=1, keepdims=True)
array([[0],
       [1],
       [2],
       [1],
       [2]])
>>> np.sum(a, axis=1, keepdims=False)
array([0, 1, 2, 1, 2])
>>> np.sum(a, axis=0, keepdims=True)
array([[2, 4, 0]])
>>> np.sum(a, axis=0, keepdims=False)
array([2, 4, 0])

You will notice that if you don't specify an axis (1st two examples), the numerical result is the same, but the keepdims = True returned a 2D array with the number 6, whereas, the second incarnation returned a scalar. Similarly, when summing along axis 1 (across rows), a 2D array is returned again when keepdims = True. The last example, along axis 0 (down columns), shows a similar characteristic... dimensions are kept when keepdims = True.
Studying axes and their properties is critical to a full understanding of the power of NumPy when dealing with multidimensional data.

2 of 2
9

An example showing keepdims in action when working with higher dimensional arrays. Let's see how the shape of the array changes as we do different reductions:

import numpy as np
a = np.random.rand(2,3,4)
a.shape
# => (2, 3, 4)
# Note: axis=0 refers to the first dimension of size 2
#       axis=1 refers to the second dimension of size 3
#       axis=2 refers to the third dimension of size 4

a.sum(axis=0).shape
# => (3, 4)
# Simple sum over the first dimension, we "lose" that dimension 
# because we did an aggregation (sum) over it

a.sum(axis=0, keepdims=True).shape
# => (1, 3, 4)
# Same sum over the first dimension, but instead of "loosing" that 
# dimension, it becomes 1.

a.sum(axis=(0,2)).shape
# => (3,)
# Here we "lose" two dimensions

a.sum(axis=(0,2), keepdims=True).shape
# => (1, 3, 1)
# Here the two dimensions become 1 respectively
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Meaning of the axis parameter (0, 1, -1) | note.nkmk.me
January 18, 2024 - Functions and methods with the axis parameter also support the keepdims parameter. keepdims=True maintains the same number of dimensions in the output array as in the input array. np.sum() is used as an example, but the same applies to other ...
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.mean.html
numpy.mean — NumPy v2.6.dev0 Manual
If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.
🌐
Interactive Chaos
interactivechaos.com › en › python › function › numpymean
numpy.mean | Interactive Chaos
January 21, 2019 - keepdims: (Optional) Boolean. If it takes the value True, the axes that are reduced are left in the result with dimensions with size 1. ... The numpy.mean function returns a ndarray.
🌐
Programiz
programiz.com › python-programming › numpy › methods › mean
NumPy mean()
# calculate the mean of the array avg = np.mean(array1) print(avg) # Output: 3.5 ... dtype = None, i.e. in the case of integers, float is taken otherwise mean is of the same datatype as the elements. By default, keepdims and where will not be passed.
🌐
Sharp Sight
sharpsight.ai › blog › numpy-mean
How to use the NumPy mean function - Sharp Sight
February 6, 2024 - The keepdims parameter of NumPy mean enables you to control the dimensions of the output. Specifically, it enables you to make the dimensions of the output exactly the same as the dimensions of the input array.
Find elsewhere
🌐
DataCamp
datacamp.com › doc › numpy › mean
NumPy mean()
By default (axis=None), the mean is computed for the flattened array. dtype: Data type for the calculation, useful if the input array has an integer type. out: Alternative output array to place the result. keepdims: If set to True, the reduced axes are left in the result as dimensions with size one...
🌐
Codecademy
codecademy.com › docs › python:numpy › built-in functions › .mean()
Python:NumPy | Built-in Functions | .mean() | Codecademy
June 13, 2025 - No, .mean() works only with numeric data. Attempting to calculate the mean of non-numeric data will result in a TypeError. Set the keepdims=True parameter to maintain the dimensions of the original array in the output.
🌐
Saturn Cloud
saturncloud.io › blog › understanding-the-role-of-keepdims-in-numpy-for-data-scientists
Saturn Cloud | Saturn Cloud | The Control Plane for GPU Clouds
July 23, 2023 - Saturn Cloud is the white-labeled control plane for GPU clouds: multi-tenant isolation, day-2 support, and integrated billing, running in your cloud under your brand.
🌐
GitHub
github.com › numpy › numpy › issues › 6750
np.mean with keepdims=True does not work on memmap · Issue #6750 · numpy/numpy
December 1, 2015 - In [95]: data.shape Out[95]: (145, 174, 145, 288) In [101]: np.mean(data[..., 0:10], axis=-1, keepdims=True).shape Out[101]: (145, 174, 145) In [105]: type(data) Out[105]: numpy.core.memmap.memmap In [106]: data = np.array(data) In [107]: np.mean(data[..., 0:10], axis=-1, keepdims=True).shape Out[107]: (145, 174, 145, 1) So the memmap doesn't play well with the keepdims=True, but the numpy array version works as expected.
Author: numpy
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.mean.html
numpy.ndarray.mean — NumPy v2.5 Manual
ndarray.mean(axis=None, dtype=None, out=None, *, keepdims=<no value>, where=<no value>)# Returns the average of the array elements along given axis. Refer to numpy.mean for full documentation. See also · numpy.mean · equivalent function ·
🌐
JAX Documentation
docs.jax.dev › en › latest › _autosummary › jax.numpy.mean.html
jax.numpy.mean — JAX documentation
>>> jnp.mean(x, axis=1) Array([2.5, 4. , 5. ], dtype=float32) If keepdims=True, ndim of the output is equal to that of the input.
🌐
GeeksforGeeks
geeksforgeeks.org › numpy-mean-in-python
numpy.mean() in Python - GeeksforGeeks
November 28, 2018 - numpy.nanmean() function can be used to calculate the mean of array ignoring the NaN value. If array have NaN value and we can find out the mean without effect of NaN value. Syntax: numpy.nanmean(a, axis=None, dtype=None, out=None, ...
🌐
IncludeHelp
includehelp.com › python › what-does-the-keepdims-parameter-do-with-numpy-sum-function.aspx
Python - What does the 'keepdims' parameter do with numpy.sum() function?
Let us understand with the help ... Display result print("Sum:\n",res) Output: As we can see, by passing keepdims=True, the final result has the retained dimensions....
🌐
GitHub
github.com › pandas-dev › pandas › issues › 16215
keepdims fails when taking mean · Issue #16215 · pandas-dev/pandas
May 3, 2017 - The keepdims argument is ignored when taking the mean of pandas dataframes, resulting in an array of lower dimensionality. Oddly, there's no documentation for pd.DataFrame.mean suggesting keepdims should even be allowed as an argument, but it accepts it with no effect. This also modifies the behavior of np.mean.
Author: pandas-dev
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.mean.html
numpy.mean — NumPy v2.2 Manual
If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.
🌐
Alibaba Cloud
topic.alibabacloud.com › a › the-meaning-of-keepdims-in-python-numpy_1_29_30286150.html
The meaning of keepdims in Python NumPy
November 13, 2017 - Keepdims is mainly used to maintain the two-dimensional properties of matricesImport= Np.array ([[1,2],[3,4]])# is added by line and retains the second dimension of print(Np.sum (A, Axis=1, keepdims=True)# Add by line, do not maintain the second