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 5 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 via ``@`` notation. (:issue:`58041`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if "when using numpy" is clear - what do you think of doing something like

when using NumPy attributes via @ notation, e.g. df.eval("@np.floor(a)")

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated as per suggestion, thanks

- 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
7 changes: 7 additions & 0 deletions pandas/tests/computation/test_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,13 @@ def test_and_logic_string_match(self):
assert pd.eval(f"{event.str.match('hello').a}")
assert pd.eval(f"{event.str.match('hello').a and event.str.match('hello').a}")

def test_using_numpy(self):
# GH 58041
df = Series([0.2, 1.5, 2.8], name="a").to_frame()
res = df.eval("@np.floor(a)")
expected = np.floor(df["a"])
tm.assert_series_equal(expected, res, check_names=False)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you set the proper name on expected and then remove check_names=False.

Copy link
Contributor Author

@domsmrz domsmrz Apr 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, I can't. The issue is that df.eval(@np.floor(a)) will have different names in Linux unittests compared to Win/MacOS unittest. Meaning if I just remove check_names and:

  • leave as-is, the Linux unittests will fail
  • change the name of expected to "a", the Win & MacOS unittests will fail

Please see my previous comment and/or #58069 for a little bit more details.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a further thought, we can sort of work around the issue by explicitly stating the engine, which is arguably something we should do anyway. I've updated the PR accordingly -- and also moved the test into more fitting test file. Please take a look and let me know what you think.



# -------------------------------------
# gh-12388: Typecasting rules consistency with python
Expand Down