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
user8504877
- pandas has an
interpolate()functionleopardxpreload– leopardxpreload2020-06-18 13:16:14 +00:00CommentedJun 18, 2020 at 13:16
3 Answers3
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) Sign up to request clarification or add additional context in comments.
Comments
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')Comments
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
1,2881 gold badge15 silver badges30 bronze badges
