Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas interpolate only when values exist on both sides

Tags:

python

pandas

consider pd.Series s

import pandas as pd
import numpy as np

s = pd.Series([np.nan, 1, np.nan, 3, np.nan])

How do 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 to remain

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

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

like image 385
piRSquared Avatar asked Oct 28 '16 14:10

piRSquared


1 Answers

I do this - skipping the heading and tailing NAs:

s.iloc[s.first_valid_index():s.last_valid_index()+1].interpolate()
like image 114
Zeugma Avatar answered Oct 10 '22 22:10

Zeugma