Reputation:
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'.
Upvotes: 0
Views: 439
Reputation: 1622
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')
Upvotes: 0
Reputation: 1288
df2['Value_B']=df2['Value_B'].apply(pd.to_numeric).replace('',np.nan, regex=True).interpolate() #empty cells need to be Nan
Upvotes: 0
Reputation: 768
pandas interpolate()
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)
Upvotes: 1