Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/65641499/how-to-parse-a-string-calculation-in-a-pandas-dataframe-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
72 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...