Ad

Pythonic Way Of Replacing Nan Sub-array With Array Of Same Size

- 1 answer

Suppose i have given a numpy array like this:

a = np.array([1, 2, 3, 4, np.nan, 5, np.nan, 6, np.nan])
# [1, 2, 3, 4, nan, 5, nan, 6, nan]

I know the number of nan values in the array and have the according array for replacement, e.g.:

b = np.array([12, 13, 14])
# [12, 13, 14]

What is the pythonic way of substituting the array b for all the nan value, such that I get the reult:

[1, 2, 3, 4, 12, 5, 13, 6, 14]
Ad

Answer

Perform boolean indexing on a using np.isnan and replace with b as:

a[np.isnan(a)] = b

print(a)
# array([ 1.,  2.,  3.,  4., 12.,  5., 13.,  6., 14.])
Ad
source: stackoverflow.com
Ad