2

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

nandhos
  • 681
  • 2
  • 16
  • 31

1 Answers1

3

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.  ])
usethedeathstar
  • 2,219
  • 1
  • 19
  • 30
  • A[A==-999]=(A[(A==-999)-1]+A[(A==-999)+1])/2. ValueError: NumPy boolean array indexing assignment cannot assign 14 input values to the 4 output values where the mask is true – sabbahillel Apr 09 '14 at 14:20