Search code examples
pythonlinear-interpolation

How to interpolate in Python?


I want to make a linear interpolation of the column Value_B in my dataframe df2. How can I do this with python in an easy way?

df2 = pd.DataFrame(np.array([[1, 2, 10], [2, 5, ''], [3, 8, 30], [4, 2, ''], [5, 5, 50], [6, 8, '']]), columns=['Angle', 'Value_A', 'Value_B'])

df2

The result of Value_B should be 10, '20', 30, '40', 50, '60'.


Solution

  • I realized that we need to first make the columns of df2 to numeric before interpolation. Then we can follow @leopardxpreload answer

    for col in df2.columns:
        df2[col] = pd.to_numeric(df2[col], errors='coerce')
    df = df2.interpolate(method ='linear', limit_direction ='forward')