NumPy ndarray.sum()

The numpy.ndarray.sum() method calculates the sum of array elements along a specified axis. It can sum all elements in the array or along specific dimensions, and it supports additional parameters for customization.

Syntax

</>
Copy
ndarray.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)

Parameters

ParameterTypeDescription
axisNone, int, or tuple of ints, optionalAxis or axes along which a sum is performed. If None, sums all elements.
dtypedtype, optionalSpecifies the data type of the output array and accumulator.
outndarray, optionalAlternative output array to store the result.
keepdimsbool, optionalIf True, preserves the reduced dimensions as size one.
initialscalar, optionalStarting value for the sum, useful for initializing reductions.
wherearray_like of bool, optionalSpecifies elements to include in the sum.

Return Value

Returns the sum of the array elements as a scalar if axis=None, or as an array if an axis is specified. The dtype of the result depends on the input and the dtype parameter.


Examples

1. Summing All Elements in ndarray

This example demonstrates summing all elements in a NumPy array.

</>
Copy
import numpy as np

# Creating a 2D array
arr = np.array([[1, 2], 
                [3, 4]])

# Summing all elements
result = arr.sum()
print(result)  # Output: 10

Output:

10

2. Using the axis Parameter in ndarray.sum()

Summing elements along a specific axis.

</>
Copy
import numpy as np

arr = np.array([[1, 2], 
                [3, 4]])

# Summing along axis 0 (columns)
result_axis0 = arr.sum(axis=0)
print(result_axis0)  # Output: [4 6]

# Summing along axis 1 (rows)
result_axis1 = arr.sum(axis=1)
print(result_axis1)  # Output: [3 7]

Output:

[4 6]
[3 7]

3. Changing Data Type with dtype

Setting the dtype to control precision.

</>
Copy
import numpy as np

arr = np.array([1, 2, 3, 4], dtype=np.int8)

# Summing with a higher precision dtype
result = arr.sum(dtype=np.int32)
print(result)  # Output: 10 (stored as int32)

Output:

10

4. Keeping Dimensions with keepdims=True

Retaining reduced dimensions for broadcasting compatibility.

</>
Copy
import numpy as np

arr = np.array([[1, 2], 
                [3, 4]])

# Summing along axis 1 with keepdims=True
result = arr.sum(axis=1, keepdims=True)
print(result)
# Output:
# [[3]
#  [7]]

Output:

[[3]
 [7]]

5. Using the initial Parameter in ndarray.sum()

Starting the sum with an initial value.

</>
Copy
import numpy as np

arr = np.array([1, 2, 3, 4])

# Summing with an initial value of 10
result = arr.sum(initial=10)
print(result)  # Output: 20

Output:

20

Sum = initial value + 1 + 2 + 3 + 4 = 10 + 1 + 2 + 3 + 4 = 20

6. Using the where Parameter in ndarray.sum()

Summing only selected elements using a condition.

</>
Copy
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

# Mask: Only sum even numbers
mask = (arr % 2 == 0)

result = arr.sum(where=mask)
print(result)  # Output: 6 (2 + 4)

Output:

6