hks014 - 4 months ago 16
Python Question

# Linear Approximate of Data Frame

``````Block DF
0     1.2
1     2.3
4     4.2
5     5.6
6     4.3
10    2.2
``````

How to find out linear approx. value DF of Block 7

``````(7,???)
``````

using the closest two data point

``````(6, 4.3)
(10, 2.2)?
``````

How to implement to find the two closest data point?

You can use `numpy.interp` function to find interpolations:

``````import numpy as np
np.interp(7, df.block, df.DF)
# >>> 3.775
``````

You could also use `interp1d` from the `scipy.interpolate` package:

``````from scipy.interpolation import interp1d
f = interp1d(df.block, df.DF)
xnew = np.linspace(0, 10, num=11, endpoint=True)
zip(xnew, f(xnew))
# [(0.0, 1.2),
# (1.0, 2.2999999999999998),
# (2.0, 2.9333333333333331),
# (3.0, 3.5666666666666664),
# (4.0, 4.2000000000000002),
# (5.0, 5.5999999999999996),
# (6.0, 4.2999999999999998),
# (7.0, 3.7749999999999999),
# (8.0, 3.25),
# (9.0, 2.7250000000000001),
# (10.0, 2.2000000000000002)]
``````
Source (Stackoverflow)