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:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array with some NaN values
arr1 = np.array([[10, 20, 30], [40, 50, np.nan], [np.nan, 6, np.nan], [np.nan, np.nan, np.nan]])

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

# Masking the array 'arr1' where the elements are NaN
temp = np.ma.masked_array(arr1, np.isnan(arr1))

# Calculating the mean along the rows (axis=1) without considering NaN values
result = np.mean(temp, axis=1)

# Displaying the averages without NaNs along the rows and replacing masked values with NaN
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]

Explanation:

arr1 = np.array([[10, 20 ,30], [40, 50, np.nan], [np.nan, 6, np.nan], [np.nan, np.nan, np.nan]])

The above code creates a NumPy array 'arr1' with the given values, including some NaN values.

temp = np.ma.masked_array(arr1,np.isnan(arr1)): This code creates a masked array 'temp' from 'arr1' using NumPy's Masked Array module (np.ma). The mask is created using np.isnan(arr1), which generates a boolean array indicating whether each element in 'arr1' is NaN or not. In 'temp', the NaN values are masked and will be excluded from the calculations.

result = np.mean(temp, axis=1): This code calculates the mean of 'temp' along axis 1 (row-wise mean). Since 'temp' is a masked array, the NaN values are excluded from the mean calculation.

print(result.filled(np.nan)): Replace the masked values in 'result' with NaN using the filled() method and print the final result. This will display the row-wise mean of 'arr1', excluding the NaN values.

Pictorial Presentation:

NumPy: Calculate averages without NaNs along a given array

Python-Numpy Code Editor:

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



Follow us on Facebook and Twitter for latest update.