Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...