w3resource

NumPy: Calculate mean across dimension, in a 2D numpy array


Write a NumPy program to calculate mean across dimension, in a 2D numpy array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a 2x2 NumPy array
x = np.array([[10, 30], [20, 60]])

# Displaying the original array
print("Original array:")
print(x)

# Computing the mean of each column using axis 0 (column-wise)
print("Mean of each column:")
print(x.mean(axis=0))

# Computing the mean of each row using axis 1 (row-wise)
print("Mean of each row:")
print(x.mean(axis=1)) 

Sample Output:

Original array:                                                        
[[10 30]                                                               
 [20 60]]
Mean of each column:                              
[ 15.  45.]                                                            
Mean of each row:                                                   
[ 20.  40.]

Explanation:

In the above code –

x = np.array([[10, 30], [20, 60]]) - The NumPy array x is a 2-dimensional array with shape (2, 2). It has 2 rows and 2 columns. The first row contains the elements 10 and 30, and the second row contains the elements 20 and 60.

x.mean(axis=0) -> This line computes the mean of each column of the x array. The axis=0 argument specifies the axis along which the mean is computed. Since axis=0 is specified, the mean is computed along the rows of the array. Thus, it returns an array with shape (2,) containing the means of the two columns of the x array.

x.mean(axis=1) –> This line computes the mean of each row of the x array. The axis=1 argument specifies the axis along which the mean is computed. Since axis=1 is specified, the mean is computed along the columns of the array. Thus, it returns an array with shape (2,) containing the means of the two rows of the x array.

Pictorial Presentation:

NumPy Mathematics: Calculate mean across dimension, in a 2D numpy array.

Python-Numpy Code Editor: