Ad

How To Linearly Interpolate A New Column From Existing Columns?

- 1 answer

I am trying to use the values in two available columns for linearly interpolating a new column. I am using np.interp, but it gives an error about fp. Can anyone suggest a way using pandas or numpy for such a linear interpolation?

X1      X2
34.5    36.3
12.4    11.3
16.5    15.9
8.5      8.1
56.6    55.6


df['intreped_X'] = pd.Series(dtype='float') #adding a new column with NaN
df['intreped_X'] = np.interp(df['X1'].values,
                           df['X2'].values)

Error: TypeError: _interp_dispatcher() missing 1 required positional argument: 'fp'.

Update: I also tested the following script from this link, but does not produce new values in the new column and just adds the "bound method NDFrame.interpolate ..." in each row.

df['intreped_X'] = np.NaN
df = df.fillna(df.interpolate, axis=1)
print(df)

     X1                   intreped_X                     X2
0   34.5    <bound method NDFrame.interpolate of A ...  36.3
1   12.4    <bound method NDFrame.interpolate of A ...  11.3
2   16.5    <bound method NDFrame.interpolate of A ...  15.9
3   8.5     <bound method NDFrame.interpolate of A ...  8.1
4   56.6    <bound method NDFrame.interpolate of A ...  55.6
Ad

Answer

Add a new column between the two existing ones filled with NaN values and then use interpolate with axis=1:

df.insert(1, 'intreped_X', np.nan)
df.interpolate(axis=1)

Result:

      X1  intreped_X    X2
0   34.5       35.40  36.3
1   12.4       11.85  11.3
2   16.5       16.20  15.9
3   8.5         8.30   8.1
4   56.6       56.10  55.6
Ad
source: stackoverflow.com
Ad