Mean is the sum of all the elements of an array or list divided by the total number of elements. Do you wants to find the mean of each row of numpy array in python ? . If yes then this post is for you. In this tutorial you will know all the steps to Calculate Mean of each row in python numpy.
Steps to Calculate Mean of each row in python numpy
In this section you will know all the steps to calculate the mean of each row in numpy array.
Step 1: Import NumPy
The first step is to start by importing the NumPy library. You can import the numpy library using the import statement.
import numpy as np
Step 2: Create a 2D NumPy array
For demonstration purpose lets create a 2D numpy array. You can create numpy array using the np.array() function.
data = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
Step 3: Calculate the mean along the rows
To calculate the mean along the rows you have to use the np.mean function with axis=1. It will sum all the elements of the rows to find the mean.
row_means = np.mean(data, axis=1)
axis=1 argument specifies that the mean should be calculated along the second axis (columns), which corresponds to the rows in a 2D array.
Step 4: Print or display the result
Finally, display or use the
row_means array wherever you want to use the variable.
print("Mean of each row:", row_means)
import numpy as np # Step 2: Create a 2D NumPy array data = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) # Step 3: Calculate the mean along the rows row_means = np.mean(data, axis=1) # Step 4: Print or use the result print("Mean of each row:", row_means)
Mean of each row: [20. 50. 80.]
You can easily calculate the mean of each row of the numpy array using the np.mean() with defined axis parameter. The above steps will easily find the mean of each row. There may be another methods also but the above method is the best.