w3resource

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

NumPy Mathematics: Exercise-19 with Solution

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:

Previous: Write a NumPy program to add one polynomial to another, subtract one polynomial from another, multiply one polynomial by another and divide one polynomial by another.
Next: Write a NumPy program to create a random array with 1000 elements and compute the average, variance, standard deviation of the array elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-19.php