Input missed values with mean of nearest neighbors in column

Viewed 4989

I have a DataFrame:

df = pd.DataFrame(data=[676, 0, 670, 0, 668], index=['2012-01-31 00:00:00','2012-02-29 00:00:00',
                                                     '2012-03-31 00:00:00','2012-04-30 00:00:00',
                                                     '2012-05-31 00:00:00'])  
df.index.name = "Date"
df.columns = ["Number"]

Which looks like:

              Number
Date    
2012-01-31 00:00:00 676
2012-02-29 00:00:00 0
2012-03-31 00:00:00 670
2012-04-30 00:00:00 0
2012-05-31 00:00:00 668

How can i input 2nd and 4th values with (676+670)/2 and (670+668)/2 correspondinly?

I can save values as np.array and imput them in array, but that's rediculous!

4 Answers

@spies006 answer can be adapted to:

df.where(df.replace(to_replace=0, value=np.nan).isna(), other=(df.fillna(method='ffill') + df.fillna(method='bfill'))/2)

It can be simplified to this:

df.where(df.values == 0, other=(df.fillna(method='ffill') + df.fillna(method='bfill'))/2)

I would use the replace() method to replace the 0's with np.nan and then use the method interpolate():

df.replace(to_replace=0, value=np.nan, inplace=True)
df.interpolate(inplace=True)

                     Number
Date                       
2012-01-31 00:00:00   676.0
2012-02-29 00:00:00   673.0
2012-03-31 00:00:00   670.0
2012-04-30 00:00:00   669.0
2012-05-31 00:00:00   668.0
Related