We use np.sum() to add up numbers in arrays quickly. The axis parameter helps us choose how to add: across rows, columns, or the whole array.
0
0
np.sum() and axis parameter in NumPy
Introduction
Adding all sales numbers in a table to get total sales.
Summing scores of each student across subjects to get total marks.
Calculating total pixels brightness in each row or column of an image.
Finding total expenses per category from a budget spreadsheet.
Syntax
NumPy
np.sum(array, axis=None)
array is the data you want to add up.
axis=None sums all elements into one number.
axis=0 sums down columns (vertical).
axis=1 sums across rows (horizontal).
Examples
Adds every number in the array to get one total.
NumPy
np.sum(arr) # sums all elements in arr
Adds numbers down each column, returns sums per column.
NumPy
np.sum(arr, axis=0) # sums each column
Adds numbers across each row, returns sums per row.
NumPy
np.sum(arr, axis=1) # sums each row
Sample Program
This code creates a 3x3 array. It sums all numbers, then sums each column, and then sums each row. It prints all results clearly.
NumPy
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Sum all elements total_sum = np.sum(arr) # Sum down columns (axis=0) sum_columns = np.sum(arr, axis=0) # Sum across rows (axis=1) sum_rows = np.sum(arr, axis=1) print(f"Total sum: {total_sum}") print(f"Sum of each column: {sum_columns}") print(f"Sum of each row: {sum_rows}")
OutputSuccess
Important Notes
If you forget axis, it adds everything into one number.
For 2D arrays, axis=0 means down columns, axis=1 means across rows.
For higher dimensions, axis chooses which dimension to sum over.
Summary
np.sum() adds numbers in arrays.
The axis parameter controls the direction of addition.
Use axis=0 for columns, axis=1 for rows, or None for all elements.