How to Calculate Mean Across the Row or Column in a NumPy Array
Let’s see how we can calculate the mean across the row or column in a NumPy array using the mean()
function.
Suppose we’re operating on the following NumPy array.
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
1. Calculating the Mean Across the Row
To calculate the mean across the row, we can use the mean()
function along the axis 0
. This will give us the mean value of each row in the array.
mean_row = np.mean(arr, axis=0)
# [4. 5. 6.]
2. Calculating the Mean Across the Column
To calculate the mean across the column, we can use the mean()
function along the axis 1
. This will give us the mean value of each column in the array.
mean_column = np.mean(arr, axis=1)
# [2. 5. 8.]
3. Calculating the Mean of the Entire Array
To calculate the mean of the entire array, we can use the mean()
function without specifying any axis. This will give us the mean value of all the elements in the array.
mean_array = np.mean(arr)
# 5.0