CMASolutions
CMASolutions

Reputation: 3

How to parse a string calculation in a pandas dataframe column

I am trying to parse a string calculation which is a column within a dataframe, if the calculation is static I can use the eval function. However this doesnt appear to work when you give it a column name.

import pandas as pd

calcs = {'a': [1,1],
         'b': [1,1],
         'c': [1,1],
         'calc': ['result=a*b','result=a+b']}

df = pd.DataFrame(calcs, columns = ['a', 'b','c','calc'])
 
print(df)
 
a b c calc
1 1 1 a*b
1 1 1 a+b

can you please tell me how it would be possible to evaluate the calculation in the 'calc' column for each row in the dataframe.

Upvotes: 0

Views: 340

Answers (1)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can df.apply, df.eval:

>>> df['result'] = df.apply(lambda x:x.to_frame().T.eval(x[-1]).item(), axis=1)
>>> df
   a  b  c calc  result
0  1  1  1  a*b       1
1  1  1  1  a+b       2

Or use np.diag:

>>> import numpy as np
>>> df['result'] = np.diag(df.eval(df['calc']))
>>> df
   a  b  c calc  result
0  1  1  1  a*b       1
1  1  1  1  a+b       2

Upvotes: 1

Related Questions