1
$\begingroup$

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.

$\endgroup$

2 Answers 2

4
$\begingroup$

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
$\endgroup$
1
  • $\begingroup$ This my hackish solution. Would like to know if there is a more elegent solution. $\endgroup$ Commented Nov 16, 2017 at 5:06
1
$\begingroup$

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
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.