w3resource

NumPy: Calculate averages without NaNs along a given array

NumPy: Array Object Exercise-156 with Solution

Write a NumPy program to calculate averages without NaNs along a given array.

Sample Solution:

Python Code:

import numpy as np
arr1 = np.array([[10, 20 ,30], [40, 50, np.nan], [np.nan, 6, np.nan], [np.nan, np.nan, np.nan]])
print("Original array:")
print(arr1)
temp = np.ma.masked_array(arr1,np.isnan(arr1))
result = np.mean(temp, axis=1)
print("Averages without NaNs along the said array:")
print(result.filled(np.nan))

Sample Output:

Original array:
[[10. 20. 30.]
 [40. 50. nan]
 [nan  6. nan]
 [nan nan nan]]
Averages without NaNs along the said array:
[20. 45.  6. nan]

Pictorial Presentation:

NumPy: Calculate averages without NaNs along a given array

Python Code Editor:

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

Previous: Write a NumPy program to check whether a Numpy array contains a specified row.
Next: Write a NumPy program to create a new array which is the average of every consecutive triplet of elements of a given array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}