w3resource

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


19. Mean Across Dimensions in 2D 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.

For more Practice: Solve these Related Problems:

  • Implement a function that computes the mean of each column and each row in a 2D array using np.mean with appropriate axes.
  • Test the function on both integer and float arrays and verify that the computed means are correct.
  • Create a solution that returns the row means and column means as a tuple of arrays.
  • Apply the function on a transposed array and compare the results to ensure consistency.

Go to:


PREV : Polynomial Arithmetic Operations
NEXT : Statistics on a Random Array

Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.