Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Get Matrix Mean
When working with matrices in Python, calculating the mean (average) of all elements is a common operation. The NumPy package provides the mean() method to efficiently compute the mean of matrix elements.
Basic Matrix Mean
Here's how to calculate the mean of all elements in a matrix ?
import numpy as np
my_matrix = np.matrix('24 41; 35 25')
print("The matrix is:")
print(my_matrix)
my_result = my_matrix.mean()
print("The mean is:")
print(my_result)
The matrix is: [[24 41] [35 25]] The mean is: 31.25
Mean Along Specific Axis
You can calculate the mean along rows (axis=1) or columns (axis=0) ?
import numpy as np
matrix = np.matrix('10 20 30; 40 50 60; 70 80 90')
print("Original matrix:")
print(matrix)
# Mean of each row
row_means = matrix.mean(axis=1)
print("\nMean of each row:")
print(row_means)
# Mean of each column
col_means = matrix.mean(axis=0)
print("\nMean of each column:")
print(col_means)
Original matrix: [[10 20 30] [40 50 60] [70 80 90]] Mean of each row: [[20.] [50.] [80.]] Mean of each column: [[40. 50. 60.]]
Key Parameters
The mean() method accepts these important parameters:
- axis: None (default, all elements), 0 (column-wise), 1 (row-wise)
- dtype: Data type for the result
- out: Output array to store the result
Conclusion
Use matrix.mean() to calculate the overall mean, or specify axis=0 for column means and axis=1 for row means. NumPy's mean method provides efficient computation for matrix statistics.
Advertisements
