I have a NumPy array a
like the following:
>>> str(a)
\'[ nan nan nan 1.44955726 1.44628034 1.44409573\\n 1.4408
Here is a solution using simple python iterators. They are actually more efficient here than numpy.where
, especially with big arrays! See comparison of similar code here.
import numpy as np
a = np.array([np.NAN, np.NAN, np.NAN, 1.44955726, 1.44628034, 1.44409573, 1.4408188, 1.43657094, 1.43171624, 1.42649744, 1.42200684, 1.42117704, 1.42040255, 1.41922908, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN])
mask = np.isfinite(a)
# get first value in list
for i in range(len(mask)):
if mask[i]:
first = i
break
# get last vaue in list
for i in range(len(mask)-1, -1, -1):
if mask[i]:
last = i
break
# fill NaN with near known value on the edges
a = np.copy(a)
a[:first] = a[first]
a[last + 1:] = a[last]
print(a)
Output:
[1.44955726 1.44955726 1.44955726 1.44955726 1.44628034 1.44409573
1.4408188 1.43657094 1.43171624 1.42649744 1.42200684 1.42117704
1.42040255 1.41922908 1.41922908 1.41922908 1.41922908 1.41922908
1.41922908 1.41922908]
It replaces only the first and last NaNs like requested here.