EthanMcQ
EthanMcQ

Reputation: 31

How to interpolate values between points

I have this dataset show below

temp = [0.1, 1, 4, 10, 15, 20, 25, 30, 35, 40]
sg =[0.999850, 0.999902, 0.999975, 0.999703, 0.999103, 0.998207, 0.997047, 0.995649, 0.99403, 0.99222]

sg_temp = pd.DataFrame({'temp' : temp,
                        'sg' : sg})
 temp        sg
0   0.1  0.999850
1   1.0  0.999902
2   4.0  0.999975
3  10.0  0.999703
4  15.0  0.999103
5  20.0  0.998207
6  25.0  0.997047
7  30.0  0.995649
8  35.0  0.994030
9  40.0  0.992220

I would like to interpolate all the values between 0.1 and 40 on a scale of 0.001 with a spline interpolation and have those points as in the dataframe as well. I have used resample() before but can't seem to find an equivalent for this case.

I have tried this based off of other questions but it doesn't work.

scale = np.linspace(0, 40, 40*1000)
interpolation_sg = interpolate.CubicSpline(list(sg_temp.temp), list(sg_temp.sg))

Upvotes: 0

Views: 916

Answers (2)

mozway
mozway

Reputation: 262234

Call scale with the result of the interpolation:

from scipy import interpolate

out  = pd.DataFrame(
 {'temp': scale,
  'sg': interpolate.CubicSpline(sg_temp['temp'],
                                sg_temp['sg'])(scale)
 })

Visual output:

enter image description here

Code for the plot

ax = plt.subplot()
out.plot(x='temp', y='sg', label='interpolated', ax=ax)
sg_temp.plot(x='temp', y='sg', marker='o', label='sg', ls='', ax=ax)

Upvotes: 1

sunnytown
sunnytown

Reputation: 1996

It works very well for me. What exactly does not work for you? Have you correctly used the returned CubicSpline to generate your interpolated values? Or is there some kind of error?

Basically you obtain your interpolated y values by plugging in the new x values (scale) to your returned CubicSpline function:

y = interpolation_sg(scale)

I believe this is the issue here. You probably expect that the interpolation function returns you the values, but it returns a function. And you use this function to obtain your values.

If I plot this, I obtain this graph:

import matplotlib.pyplot as plt
plt.plot(sg_temp['temp'], sg_temp['sg'], marker='o', ls='') # Plots the originial data
plt.plot(scale, interpolation_sg(scale)) # Plots the interpolated data

enter image description here

Upvotes: 1

Related Questions