Home > Net >  How to convert assignment operator string to actual assignment operation
How to convert assignment operator string to actual assignment operation

Time:06-13

I am writing all my conditions in a notepad for now so that I can access that file and use anytime for any change in condition for my dataframe. My notepad txt file looks like below:

cond1 = (df['A'] == 1)
cond2 = (df['B'] >= 50)

When I read the text file, I get something like below:

["cond1 = (df['A] == 1)", "cond2 = (df['B] >= 50)"]

I wanted to convert this list to actual assignment operation. Like after execution, cond1 variable should be created and also cond2 as well. In case there are better way than storing in txt file, please advice as well.

Thank you

CodePudding user response:

I guess you can use eval() or exec() functions. Check out this article https://medium.com/@codingpilot25/difference-between-eval-and-exec-in-python-b387b25207d2#:~:text=Eval() only evaluates the,() it will throw error.

  1. exec() can be used to assign a value to variable, but eval() will throw error.
  2. eval() only evaluates the single expression, not the complex logic code, whereas exec() can be used to execute any number of expression.
  3. exec() accept the source code which contains statements like, for, while, print, import, class, if we pass these statement to eval() it will throw error.
  4. eval() function evaluates the python code and returns the value, but exec() execute the code and always returns None,

CodePudding user response:

I think you can create 4 columns in csv:

col,op,val,new
A,==,1,cond1
B,>=,50,cond2

Then create DataFrame:

df = pd.read_csv(file)

Last use operators for new columns:

import operator

ops = {'>': operator.gt,
       '<': operator.lt,
       '>=': operator.ge,
       '<=': operator.le,
       '==': operator.eq,
       '!=': operator.ne}

df1 = pd.DataFrame({'A':[10,200,1], 'B':[200,1,10]})

for c,op,y,n in zip(df['col'], df['op'], df['val'], df['new']):
    df1[n] = ops[op](df1[c], y) 

print (df1)
     A    B  cond1  cond2
0   10  200  False   True
1  200    1  False  False
2    1   10   True  False
  • Related