0

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'.

askedJun 18, 2020 at 13:11
1
  • pandas has aninterpolate() functionCommentedJun 18, 2020 at 13:16

3 Answers3

1

pandasinterpolate() function

df2.interpolate(method ='linear', limit_direction ='forward')

You can even interpolate backwards and set limits

df.interpolate(method ='linear', limit_direction ='backward', limit = 1)
answeredJun 18, 2020 at 13:16
leopardxpreload's user avatar
Sign up to request clarification or add additional context in comments.

Comments

0

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')
answeredJun 18, 2020 at 13:21
Vinod Kumar's user avatar

Comments

0
df2['Value_B']=df2['Value_B'].apply(pd.to_numeric).replace('',np.nan, regex=True).interpolate() #empty cells need to be Nan
answeredJun 18, 2020 at 13:30
JALO - JusAnotherLivngOrganism's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.