Skip to content

BUG: Allow using numpy in DataFrame.eval and DataFrame.query via @-notation #58057

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ Bug fixes
- Fixed bug in :class:`SparseDtype` for equal comparison with na fill value. (:issue:`54770`)
- Fixed bug in :meth:`.DataFrameGroupBy.median` where nat values gave an incorrect result. (:issue:`57926`)
- Fixed bug in :meth:`DataFrame.cumsum` which was raising ``IndexError`` if dtype is ``timedelta64[ns]`` (:issue:`57956`)
- Fixed bug in :meth:`DataFrame.eval` and :meth:`DataFrame.query` which caused an exception when using NumPy attributes via ``@`` notation, e.g., ``df.eval("@np.floor(a)")``. (:issue:`58041`)
- Fixed bug in :meth:`DataFrame.join` inconsistently setting result index name (:issue:`55815`)
- Fixed bug in :meth:`DataFrame.to_string` that raised ``StopIteration`` with nested DataFrames. (:issue:`16098`)
- Fixed bug in :meth:`DataFrame.transform` that was returning the wrong order unless the index was monotonically increasing. (:issue:`57069`)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/computation/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def _resolve_name(self):
res = self.env.resolve(local_name, is_local=is_local)
self.update(res)

if hasattr(res, "ndim") and res.ndim > 2:
if hasattr(res, "ndim") and isinstance(res.ndim, int) and res.ndim > 2:
raise NotImplementedError(
"N-dimensional objects, where N > 2, are not supported with eval"
)
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/frame/test_query_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,16 @@ def test_eval_object_dtype_binop(self):
expected = DataFrame({"a1": ["Y", "N"], "c": [True, False]})
tm.assert_frame_equal(res, expected)

def test_using_numpy(self, engine, parser):
# GH 58041
skip_if_no_pandas_parser(parser)
df = Series([0.2, 1.5, 2.8], name="a").to_frame()
res = df.eval("@np.floor(a)", engine=engine, parser=parser)
expected = np.floor(df["a"])
if engine == "numexpr":
expected.name = None # See GH 58069
tm.assert_series_equal(expected, res)


class TestDataFrameQueryWithMultiIndex:
def test_query_with_named_multiindex(self, parser, engine):
Expand Down