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
  • $\begingroup$ This my hackish solution. Would like to know if there is a more elegent solution. $\endgroup$ – Louis T 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
0    NaN
1    NaN
2    1.0
3    0.0
4    2.0
5    NaN
dtype: float64

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.