Say I have three columns
1,2,3 with values -5, 5, 15
I need to find where 0 lies between the columns and make it a new column
Here the answer would be 1.5 (halfway between column 1 and 2)
How to do linear interpolation in python to do this for many rows?
Needs to incorporate all 3 columns, so could get an answer like 2.2
If greater than 3, can extrapolate or otherwise just put 3 or na
Thanks!
You can use numpy.interp
for each row. If the target is outside the bounds, you'll get the closest x
value.
Example:
df = pd.DataFrame([[-5, 5, 15], [-5, -2, 6],[1, 2, 3], [-3, -2, -1]],
columns=[1,2,3])
df['x_at_0'] = [np.interp(0, xp, df.columns) for xp in df.to_numpy()]
Output:
1 2 3 x_at_0
0 -5 5 15 1.50
1 -5 -2 6 2.25
2 1 2 3 1.00
3 -3 -2 -1 3.00