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
ndarray.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
Parameters
Parameter | Type | Description |
---|---|---|
axis | None, int, or tuple of ints, optional | Axis or axes along which a sum is performed. If None , sums all elements. |
dtype | dtype, optional | Specifies the data type of the output array and accumulator. |
out | ndarray, optional | Alternative output array to store the result. |
keepdims | bool, optional | If True , preserves the reduced dimensions as size one. |
initial | scalar, optional | Starting value for the sum, useful for initializing reductions. |
where | array_like of bool, optional | Specifies 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.
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.
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.
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.
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.
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.
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