# Python Pandas - Interpolation with fixed value

Say we have a pandas series with the following values

[np.nan, np.nan, 1, np.nan, 2, np.nan]

What is the most efficient way fill the nan value with 0 in the middle. so we have

[np.nan, np.nan, 1, 0, 2, np.nan]

In other word, how to we do interpolation with a fixed value, or a .fillna operation but ignore the nan at the beginning and end of the array.

Current solution, I am using

def interpolate_with_fixed(s, value=0):
i = s.first_valid_index()
j = s.last_valid_index()
s.loc[i:j].fillna(value, inplace=True)
return s

• This my hackish solution. Would like to know if there is a more elegent solution. Nov 16 '17 at 5:06

I think your solution is quite idiomatic. Here is an alternative solution:

In [355]: s.loc[s.notnull().idxmax() : s[::-1].notnull().idxmax()].fillna(0, inplace=True)

In [356]: s
Out[356]:
0    NaN
1    NaN
2    1.0
3    0.0
4    2.0
5    NaN
dtype: float64