How to Use sum in NumPy: Syntax and Examples
Use
numpy.sum() to add all elements of an array or along a specific axis. You can specify the axis to sum rows or columns, or leave it out to sum all elements.Syntax
The basic syntax of numpy.sum() is:
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False)
Where:
a: input array to sum.axis: axis or axes along which to sum.Nonesums all elements.dtype: data type for the output (optional).out: alternative output array to store result (optional).keepdims: ifTrue, keeps reduced dimensions as size 1 (optional).
python
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False)
Example
This example shows how to sum all elements of a 2D array and how to sum along rows or columns using the axis parameter.
python
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) # Sum all elements total_sum = np.sum(arr) # Sum along columns (axis=0) sum_columns = np.sum(arr, axis=0) # Sum along rows (axis=1) sum_rows = np.sum(arr, axis=1) print('Total sum:', total_sum) print('Sum of columns:', sum_columns) print('Sum of rows:', sum_rows)
Output
Total sum: 21
Sum of columns: [5 7 9]
Sum of rows: [ 6 15]
Common Pitfalls
Common mistakes when using numpy.sum() include:
- Forgetting to specify
axiswhen you want to sum along rows or columns, which sums all elements instead. - Using the wrong axis number (remember:
axis=0sums down columns,axis=1sums across rows). - Not understanding that the result shape changes when summing along an axis.
python
import numpy as np arr = np.array([[1, 2], [3, 4]]) # Wrong: sums all elements instead of rows wrong_sum = np.sum(arr) # Right: sum along rows right_sum = np.sum(arr, axis=1) print('Wrong sum (all elements):', wrong_sum) print('Right sum (rows):', right_sum)
Output
Wrong sum (all elements): 10
Right sum (rows): [3 7]
Quick Reference
Remember these tips when using numpy.sum():
- Use
axis=None(default) to sum all elements. - Use
axis=0to sum down columns. - Use
axis=1to sum across rows. keepdims=Truekeeps the summed dimensions for broadcasting.
Key Takeaways
Use numpy.sum() to add elements of arrays easily.
Specify axis to sum along rows (axis=1) or columns (axis=0).
Without axis, sum adds all elements into a single number.
Keepdims=True keeps the dimensions after summing for easier broadcasting.
Check your axis carefully to avoid unexpected results.