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
eval?exec()did not work, so I couldn't forsee thateval()would work.