AnsFourtyTwo
AnsFourtyTwo

Reputation: 2518

Pythonic way of replacing nan sub-array with array of same size

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]

Upvotes: 2

Views: 82

Answers (1)

yatu
yatu

Reputation: 88276

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.])

Upvotes: 6

Related Questions