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:

import numpy as np
x = np.array([[10, 30], [20, 60]])
print("Original array:")
print(x)
print("Mean of each column:")
print(x.mean(axis=0))
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.]

Pictorial Presentation:

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

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

Getting rid of unwanted characters:

You can get rid of whitespaces or any specific character using strip methods in Python. You can use either plain strip for both sides, lstrip for the left side and rstrip for the right side only.

str="+++Welcome python+++"
str.strip()

print(str)

Output:

+++Welcome python+++