pythonpandaseval

Why pandas.eval() string comparison returns False


Could someone explain me why this simple piece of code returns False? That's probably pretty simple, but I don't understand why it behaves like that:

import pandas as pd

eval_string = '"abc"=="abc"'
print(pd.eval(eval_string, parser='pandas'))  # False

Note that it I try to use string's eq() function instead, it behaves as I expect.

Can be run online here: https://onecompiler.com/python/3zhsnud82

Thanks in advance for your help.


Solution

  • pandas.eval does not support scalar comparison.

    This Python syntax is not allowed:

    • Expressions
      • ...
      • Boolean expressions consisting of only scalar values

    Pass it unsupported syntax, and Pandas makes no promises about what you'll get back. (That includes not promising to give wrong results. The fact that pandas.eval('4==4') happens to give True doesn't mean it's supported.)

    pandas.eval is a specialized tool for evaluating specific sorts of expressions on large dataframes. It should not be used for running general Python code.