Pandas interpolate only if there are values ​​on both sides

consider pd.Series s

 import pandas as pd import numpy as np s = pd.Series([np.nan, 1, np.nan, 3, np.nan]) 

How can I interpolate to get:

 pd.Series([np.nan, 1, 2, 3, np.nan]) 0 NaN 1 1.0 2 2.0 3 3.0 4 NaN dtype: float64 

note: I want the first and last np.nan remain

I only want to fill in the values ​​when I have the values ​​on both sides to do the interpolation.

In other words, I want to interpolate, not extrapolate.

+8
python pandas
source share
1 answer

I do this - skipping the header and tail of the NAs:

 s.iloc[s.first_valid_index():s.last_valid_index()+1].interpolate() 
+8
source share

All Articles