Skip to content

BUG: eval fails for ExtensionArray #58748

Closed
@mutricyl

Description

@mutricyl

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

df = pd.DataFrame({'a': pd.array([1, 2, 3]), 'b': pd.array([4, 5, 6])})

# this works as expected
print(df['a'] / df['b'])
"""
0    0.25
1     0.4
2     0.5
dtype: Float64
"""

# this is not working
print(df.eval('a / b'))
"""
TypeError: Cannot interpret 'Int64Dtype()' as a data type
"""

Issue Description

This issue is coming from pint-pandas#137. ExtensionArray is used for this project and df.eval inlcuding division (\) fails with TypeError.

I was able to able to reproduce the pint-pandas issue with pandas build in IntegerArray as shown in the above example

Traceback (most recent call last):
  File "c:\CALC\DEV\pint pandas debug\test.py", line 17, in <module>
    print(df.eval('a / b'))
          ^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\frame.py", line 4738, in eval
    return _eval(expr, inplace=inplace, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\eval.py", line 340, in eval
    parsed_expr = Expr(expr, engine=engine, parser=parser, env=env)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 809, in __init__
    self.terms = self.parse()
                 ^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 828, in parse
    return self._visitor.visit(self.expr)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 413, in visit
    return visitor(node, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 419, in visit_Module
    return self.visit(expr, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 413, in visit
    return visitor(node, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 422, in visit_Expr
    return self.visit(node.value, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 413, in visit
    return visitor(node, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 535, in visit_BinOp
    return self._maybe_evaluate_binop(op, op_class, left, right)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 502, in _maybe_evaluate_binop
    res = op(lhs, rhs)
          ^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\expr.py", line 538, in <lambda>
    return lambda lhs, rhs: Div(lhs, rhs)
                            ^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\ops.py", line 528, in __init__
    if not isnumeric(lhs.return_type) or not isnumeric(rhs.return_type):
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\laurent.mutricy\AppData\Local\miniconda3\Lib\site-packages\pandas\core\computation\ops.py", line 512, in isnumeric
    return issubclass(np.dtype(dtype).type, np.number)
                      ^^^^^^^^^^^^^^^
TypeError: Cannot interpret 'Int64Dtype()' as a data type

Looking at the traceback it seams that pandas\core\computation\ops.isnumeric() does not handle properly dtypes from ExtensionArray class (or subclass). It was suggested to consider _is_numeric class attribute.

def isnumeric(dtype) -> bool:
-    return issubclass(np.dtype(dtype).type, np.number)
+   return getattr(dtype, '_is_numeric', False) or issubclass(np.dtype(dtype).type, np.number)

probably linked to #21374

Expected Behavior

df.eval('a / b') should give the same result than df['a'] / df['b']

Installed Versions

INSTALLED VERSIONS

commit : 4fb94bb
python : 3.11.4.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19045
machine : AMD64
processor : Intel64 Family 6 Model 186 Stepping 2, GenuineIntel
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : fr_FR.cp1252

pandas : 3.0.0.dev0+983.g4fb94bb09a
numpy : 1.26.4
pytz : 2024.1
dateutil : 2.8.2
setuptools : 67.8.0
pip : 23.1.2
Cython : None
pytest : 8.2.0
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.8.3
numba : None
numexpr : 2.10.0
odfpy : None
openpyxl : 3.1.2
pyarrow : 15.0.0
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.12.0
sqlalchemy : None
tables : None
tabulate : 0.9.0
xarray : 2024.2.0
xlrd : None
zstandard : 0.19.0
tzdata : 2023.3
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugExtensionArrayExtending pandas with custom dtypes or arrays.expressionspd.eval, query

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions