﻿ NumPy: Replace all the nan of a given array with the mean of another array - w3resource # NumPy: Replace all the nan of a given array with the mean of another array

## NumPy: Array Object Exercise-178 with Solution

Write a NumPy program to replace all the nan (missing values) of a given array with the mean of another array.

Sample Solution:

Python Code:

``````import numpy as np
array_nums1 = np.arange(20).reshape(4,5)
array_nums2 = np.array([[1,2,np.nan],[4,5,6],[np.nan, 7, np.nan]])
print("Original arrays:")
print(array_nums1)
print(array_nums2)
print("\nAll the nan of array_nums2 replaced by the mean of array_nums1:")
array_nums2[np.isnan(array_nums2)]= np.nanmean(array_nums1)
print(array_nums2)
```
```

Sample Output:

```Original arrays:
[[ 0  1  2  3  4]
[ 5  6  7  8  9]
[10 11 12 13 14]
[15 16 17 18 19]]
[[ 1.  2. nan]
[ 4.  5.  6.]
[nan  7. nan]]

All the nan of array_nums2 replaced by the mean of array_nums1:
[[1.  2.  9.5]
[4.  5.  6. ]
[9.5 7.  9.5]]
```

Python Code Editor:

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

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}
```