5

What is the most efficient numpy way to replace masked values in an array with the average of the closest unmasked values next to them?

eg:

a = np.array([2,6,4,8])
b = np.ma.masked_where(a>5,a)
print b

masked_array(data = [2 -- 4 --],
         mask = [False  True False  True],
   fill_value = 999999)

I want the masked values in b to be replaced with the average of values just next to them. Boundaries can repeat the closest unmasked value. So in this example, b will be the following:

b = [2,3,4,4]

The main reason for this question is to see whether this can be done efficiently without the use of an iterator.

firefly
  • 953
  • 2
  • 11
  • 18

1 Answers1

-1

you can use np.interp and np.where

import numpy as np

a = np.array([2,6,4,8])
mymask = a>5
b = np.ma.masked_where(mymask,a)

print b
# [2 -- 4 --]

c = np.interp(np.where(mymask)[0],np.where(~mymask)[0],b[np.where(~mymask)[0]])
b[np.where(mymask)[0]] = c

print b
# [2 3 4 4]
tmdavison
  • 64,360
  • 12
  • 187
  • 165