
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Mean
What is Mean?
In mathematics, the mean is the average value of a set of numbers. The most common type is the arithmetic mean, which is the sum of the numbers divided by the count of the numbers.
Other types include the geometric mean (nth root of the product of the numbers) and the harmonic mean (number of values divided by the sum of reciprocals).
These different means are used based on the nature of the data and specific needs of the analysis.
The NumPy mean() Function
The mean() function in NumPy calculates the arithmetic mean (average) of the elements in an array. By default, it computes the mean of all elements, but you can specify an axis to compute the mean along rows or columns.
It can also handle different data types and allow you to define the output type. For example, np.mean([1, 2, 3, 4]) returns 2.5.
Following is the basic syntax of the mean() function in NumPy −
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=False)
Where,
- a: The input array containing the elements for which the mean is to be calculated.
- axis: The axis along which to compute the mean. If None, it computes the mean of all the elements in the array. For multi-dimensional arrays, you can specify an axis (0 for rows, 1 for columns, etc.).
- dtype: The data type to use in computing the mean. If not specified, it defaults to the data type of the input array.
- out: A location where the result will be stored. If provided, it must be of the same shape and type as the expected output.
- keepdims: If True, the reduced axes are kept in the result as dimensions with size one. This is useful for broadcasting.
Calculating the Mean of a 1D Array
If you have a one-dimensional array, you can use the numpy.mean() function to calculate the mean of its elements. Here is an example −
import numpy as np # Define a 1D array arr = np.array([1, 2, 3, 4, 5]) # Calculate the mean of all elements mean_value = np.mean(arr) print("Mean of the array:", mean_value)
Following is the output obtained −
Mean of the array: 3.0
Mean Along a Specific Axis in a 2D Array
In a two-dimensional array, you can compute the mean along a specific axis. For example, calculating the mean along rows or columns −
import numpy as np # Define a 2D array arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Mean along rows (axis=1) mean_rows = np.mean(arr_2d, axis=1) # Mean along columns (axis=0) mean_columns = np.mean(arr_2d, axis=0) print("Mean along rows:", mean_rows) print("Mean along columns:", mean_columns)
Following is the output obtained −
Mean along rows: [2. 5. 8.] Mean along columns: [4. 5. 6.]
Calculating Mean with a Specified Data Type
You can also specify the data type in which you want the mean to be computed. This is especially useful when dealing with large numbers or when you need the result in a specific precision (such as float64). Here is an example −
import numpy as np # Define an array of integers arr_int = np.array([10, 20, 30]) # Calculate the mean with a specified data type (float64) mean_float = np.mean(arr_int, dtype=np.float64) print("Mean with dtype float64:", mean_float)
Following is the output obtained −
Mean with dtype float64: 20.0
Calculating Mean with Keepdims Parameter
The keepdims parameter helps preserve the dimensionality of the original array after the mean operation. If set to True, the result will have the same number of dimensions as the input array, but the size of the reduced axes will be one.
import numpy as np # Define a 2D array arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Mean along columns while keeping dimensions mean_keepdims = np.mean(arr_2d, axis=0, keepdims=True) print("Mean with keepdims=True:", mean_keepdims)
Following is the output obtained −
Mean with keepdims=True: [[4. 5. 6.]]
Applications of NumPy Mean
The numpy.mean() function has a wide range of applications in scientific computing, data analysis, and machine learning. Some common use cases are −
- Calculating average values in datasets: The mean provides a central value for datasets, which is crucial in statistics and data analysis to understand the data distribution.
- Feature scaling: In machine learning, computing the mean of features helps in normalization and standardization, ensuring that each feature contributes equally to the model.
- Financial analysis: Calculating the mean of financial data, such as stock prices or sales figures, helps identify trends and make informed decisions.
- Scientific measurements: The mean is used in scientific research to summarize experimental data, providing a measure of central tendency.
Optimizing the Mean Calculation
NumPy is optimized for fast array operations, and the numpy.mean() function is highly efficient. However, there are a few ways to further optimize your mean calculations −
- Using the out parameter: If you want to store the result of the mean in a pre-existing array, you can use the out parameter, which avoids creating a new array and helps save memory.
- Using axis wisely: Specify the axis only when necessary. Calculating the mean over the whole array by default is the fastest operation, but computing the mean along specific axes might be slower depending on the data.