Created
May 21, 2020 18:05
-
-
Save breuderink/00221a2d575e6749ea08e05227a3af88 to your computer and use it in GitHub Desktop.
Filling missing values with lagged observations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def lag(x, n=0): | |
observed = np.isnan(x) == False | |
observed[0] = True | |
offsets = np.flatnonzero(observed) | |
return offsets[np.maximum(np.cumsum(observed) - 1 - n, 0)] | |
if __name__ == '__main__': | |
x = np.nan * np.ones(10) | |
x[2] = 3 | |
x[3] = 5 | |
x[5] = 7 | |
print(x) | |
for l in range(3): | |
ii = lag(x, l) | |
print(ii, x[ii]) |
Author
breuderink
commented
May 21, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment