How can I filter panda data-frame based on dynamic operator passed as a variable by user from front end

I have a data frame df and it has multiple columns. One column say is amount. So it can be referred as df[‘amount’]. The user needs to see its data based on criteria (s)he pass from front end. Let’s assume (s)he passed ‘>=’ and I stored this operator in a variable (say operator_var1). And lets say (s)he also passed one threshold for amount value (say amount_threshold) we need to show the filter data-frame based on operator and threhold value like

df = df[(df['amount'] operator_var1 amount_threshold)]

But the above shows error. Any simple way to achieve this. Please suggest.

Thanks

Answer

You could take advantage of Python built-in function eval and f-strings like this:

import pandas as pd

# Toy dataframe
df = pd.DataFrame(
    {
        "term": ["Apple", "Banana", "Orange", "Pear"],
        "amount": [100, 50, 200, 25],
    }
)

# Examples of values passed from front-end
operator_var1 = ">="
amount_threshold = 75

# Filter dataframe
df = df[eval(f"df['amount'] {operator_var1} {amount_threshold}")]

print(df)
# Outputs
     term  amount
0   Apple     100
2  Orange     200

Simply be aware that the use of eval is controversial.