Question

I got an array like this

array[1,3,5,-999,3,1,6,8,-999,-999,-999,3,5,7]

The -999 number represents missing data, i'd like replace this -999 by the mean of the right and left numbers or substituting by NaN

In another questions ask for replace nan for zeros, mean, etc. Here i ask for the oposite, i wanna replace a number by nan

Was it helpful?

Solution

Replacing by nan:

A = np.array([1,3,5,-999,3,1,6,8,-999,-999,-999,3,5,7.])
A[A==-999] = np.nan

results in:

array([  1.,   3.,   5.,  nan,   3.,   1.,   6.,   8.,  nan,  nan,  nan, 3.,   5.,   7.])

If instead of that, you want to take the mean of the numbers left and right of the -999values:

A = np.array([1,3,5,-999,3,1,6,8,-999,-999,-999,3,5,7.])
A[A==-999] = np.nan
mask = np.isnan(A)
A[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), A[~mask])

results in:

array([ 1.  ,  3.  ,  5.  ,  4.  ,  3.  ,  1.  ,  6.  ,  8.  ,  6.75, 5.5 ,  4.25,  3.  ,  5.  ,  7.  ])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top