Skip to content

Commit 8b36142

Browse files
author
Khor Chean Wei
authored
Error raised message: DataFrame eval will not work with 'Timestamp' column name (#47273)
1 parent 396ad41 commit 8b36142

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

doc/source/whatsnew/v1.5.0.rst

+2
Original file line numberDiff line numberDiff line change
@@ -932,6 +932,8 @@ Conversion
932932
- Bug in :meth:`DataFrame.to_dict` for ``orient="list"`` or ``orient="index"`` was not returning native types (:issue:`46751`)
933933
- Bug in :meth:`DataFrame.apply` that returns a :class:`DataFrame` instead of a :class:`Series` when applied to an empty :class:`DataFrame` and ``axis=1`` (:issue:`39111`)
934934
- Bug when inferring the dtype from an iterable that is *not* a NumPy ``ndarray`` consisting of all NumPy unsigned integer scalars did not result in an unsigned integer dtype (:issue:`47294`)
935+
- Bug in :meth:`DataFrame.eval` when pandas objects (e.g. ``'Timestamp'``) were column names (:issue:`44603`)
936+
-
935937

936938
Strings
937939
^^^^^^^

pandas/core/computation/ops.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,14 @@ def evaluate(self, *args, **kwargs) -> Term:
9999
return self
100100

101101
def _resolve_name(self):
102-
res = self.env.resolve(self.local_name, is_local=self.is_local)
102+
local_name = str(self.local_name)
103+
is_local = self.is_local
104+
if local_name in self.env.scope and isinstance(
105+
self.env.scope[local_name], type
106+
):
107+
is_local = False
108+
109+
res = self.env.resolve(local_name, is_local=is_local)
103110
self.update(res)
104111

105112
if hasattr(res, "ndim") and res.ndim > 2:

pandas/tests/computation/test_eval.py

+22
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
_binary_ops_dict,
5050
_unary_math_ops,
5151
)
52+
from pandas.core.computation.scope import DEFAULT_GLOBALS
5253

5354

5455
@pytest.fixture(
@@ -1890,6 +1891,27 @@ def test_negate_lt_eq_le(engine, parser):
18901891
tm.assert_frame_equal(result, expected)
18911892

18921893

1894+
@pytest.mark.parametrize(
1895+
"column",
1896+
DEFAULT_GLOBALS.keys(),
1897+
)
1898+
def test_eval_no_support_column_name(request, column):
1899+
# GH 44603
1900+
if column in ["True", "False", "inf", "Inf"]:
1901+
request.node.add_marker(
1902+
pytest.mark.xfail(
1903+
raises=KeyError,
1904+
reason=f"GH 47859 DataFrame eval not supported with {column}",
1905+
)
1906+
)
1907+
1908+
df = DataFrame(np.random.randint(0, 100, size=(10, 2)), columns=[column, "col1"])
1909+
expected = df[df[column] > 6]
1910+
result = df.query(f"{column}>6")
1911+
1912+
tm.assert_frame_equal(result, expected)
1913+
1914+
18931915
class TestValidate:
18941916
@pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
18951917
def test_validate_bool_args(self, value):

0 commit comments

Comments
 (0)