1

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

user1829708
  • 73
  • 10

2 Answers2

2

Have a look at operator module, in combination with a dictionary. You can map every operator you need to use it as variable.

value = df['amount']
threshold = input('enter a threshold')

import operator
ops = {
    ">": operator.gt,
    "<": operator.lt,
    "=": operator.eq
}   
op_input = input('enter a comparison operand')
op_func = ops[op_input]
result = op_func(value, threshold)

Take a look here: https://docs.python.org/3/library/operator.html

You’ll find a list of avaliable operands.

BlackMath
  • 1,708
  • 1
  • 11
  • 14
1

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.

Laurent
  • 12,287
  • 7
  • 21
  • 37
  • I agree with you about controversial use of eval. Furthermore, the much more safe “literal_eval” doesnt work here, because it cannot evaluate an arithmetic expression. – BlackMath Aug 15 '21 at 09:35