We use np.mean() to find the average value of numbers. It helps us understand the typical value in a group of numbers.
0
0
np.mean() for average in NumPy
Introduction
To find the average score of students in a class.
To calculate the average temperature over a week.
To get the average sales amount from daily sales data.
To summarize the average height of people in a survey.
Syntax
NumPy
np.mean(array, axis=None, dtype=None, out=None, keepdims=False)
array is the list or array of numbers you want to average.
axis decides if you want the average across rows, columns, or the whole array.
Examples
Finds the average of all numbers in the list.
NumPy
np.mean([1, 2, 3, 4, 5])
Finds the average for each column.
NumPy
np.mean([[1, 2], [3, 4]], axis=0)
Finds the average for each row.
NumPy
np.mean([[1, 2], [3, 4]], axis=1)
Sample Program
This program shows how to use np.mean() to find averages of a simple list and a 2D array. It calculates the overall average, averages by columns, and averages by rows.
NumPy
import numpy as np # List of numbers numbers = [10, 20, 30, 40, 50] # Calculate average average = np.mean(numbers) print(f"Average of numbers: {average}") # 2D array example data = np.array([[1, 2, 3], [4, 5, 6]]) # Average of all elements avg_all = np.mean(data) print(f"Average of all elements: {avg_all}") # Average by columns avg_columns = np.mean(data, axis=0) print(f"Average by columns: {avg_columns}") # Average by rows avg_rows = np.mean(data, axis=1) print(f"Average by rows: {avg_rows}")
OutputSuccess
Important Notes
If your data has missing values (like np.nan), use np.nanmean() to ignore them.
Setting axis=None (default) calculates the average of all elements.
Summary
np.mean() finds the average value of numbers in arrays or lists.
You can calculate the average across the whole data or along rows or columns using the axis parameter.
It helps summarize data to understand typical values quickly.