0
0
NumpyHow-ToBeginner ยท 3 min read

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. None sums all elements.
  • dtype: data type for the output (optional).
  • out: alternative output array to store result (optional).
  • keepdims: if True, 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 axis when you want to sum along rows or columns, which sums all elements instead.
  • Using the wrong axis number (remember: axis=0 sums down columns, axis=1 sums 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=0 to sum down columns.
  • Use axis=1 to sum across rows.
  • keepdims=True keeps 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.