Mainland
Mainland

Reputation: 4564

Python Interpolate two columns data

I have two columns. I want to interpolate y-col for same interpolation in x-col.

Problem:

df = pd.DataFrame({'x':[1,3,5],'y':[10,30,50] })

df = 
   x   y
0  1  10
1  3  30
2  5  50

Expected answer:

# interpolate x values
df = 
   x   y
0  1  10
1  2  NaN
2  3  30
3  4  NaN
4  5  50

# based on x-values, interpolate y-values.
df = 
   x   y
0  1  10
1  2  20
2  3  30
3  4  40
4  5  50

Existing answer:

I cames across the existing answers that try to map/fit whole x data and then resample. This is not what I wanted. Interpolating two values at a time is sufficient here.

Upvotes: 1

Views: 992

Answers (1)

Paul
Paul

Reputation: 1897

To create your first df (interpolation based on x), you can use range. Then you can interpolate using the interpolate function.

df2 = pd.DataFrame({'x':range(df.x.min(), df.x.max()+1)}).merge(df, on='x', how='left')
df2.y = df2.y.interpolate()
df2
    x   y
0   1   10.0
1   2   20.0
2   3   30.0
3   4   40.0
4   5   50.0

Upvotes: 3

Related Questions