Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a string containing condition in python dataframe

I am filtering a DataFrame inside a function. I get multiple conditions as string arguments which I have to employ to filter the DataFrame. exec() usually helps to execute a string expression, but I am not able to fine tune it for the DataFrame.

Here is a small miniature example:

import pandas as pd
df = pd.DataFrame({'A':[30,60,90,40],'B':['X','X','X','Y']})
print(df)
      A  B
  0  30  X
  1  60  X
  2  90  X
  3  40  Y

Now, the code below gives an error naturally. My question is how we can evaluate this string expression in the function below like exectable(expression) and get the filtered DataFrame:

def func(df,cond1,cond2):
    expression = "(df.A "+cond1+") & (df.B"+cond2+")"
    print(expression) # This results in --> (df.A < 50) & (df.B == 'X')

    return df[expression]
func(df,"< 50"," == 'X'")

Desired output,

      A  B
  0  30  X
like image 402
cph_sto Avatar asked Aug 14 '26 09:08

cph_sto


1 Answers

eval is what you are looking for.

def func(df,cond1,cond2):
    expression = eval(f"(df.A {cond1}) & (df.B{cond2})")

    return df[expression]
like image 66
go2nirvana Avatar answered Aug 16 '26 23:08

go2nirvana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!