-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathinterpNaN.py
More file actions
executable file
·36 lines (31 loc) · 1.06 KB
/
interpNaN.py
File metadata and controls
executable file
·36 lines (31 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import numpy as np
def interpNaN(y,nan_ends=0):
"""
% (C) Nick Holschuh - Amherst College -- 2022 (Nick.Holschuh@gmail.com)
% Fills in NaN values using a linear interpolator
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The inputs are:
%
% y -- 1d numpy array with possible NaNs
%
%%%%%%%%%%%%%%%
% The outputs are:
%
% y -- 1d numpy array with the NaNs replaced by interpolated values
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Following: https://stackoverflow.com/questions/6518811/interpolate-nan-values-in-a-numpy-array
"""
if isinstance(y,type(np.array([]))) == 0:
if isinstance(y,type([])):
y = np.array(y)
else:
y = np.array([y])
nans = np.isnan(y)
notnans = np.where(~np.isnan(y))[0]
x = lambda z: z.nonzero()[0]
y[nans] = np.interp(x(nans), x(~nans), y[~nans])
if nan_ends == 1:
y[:notnans[0]] = np.NaN
y[notnans[-1]+1:] = np.NaN
return y