Skip to content

BUG: Fix bug when using df.query with "str.contains()" #25813

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

Closed
wants to merge 6 commits into from
Closed
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/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,7 @@ Other

- Improved :class:`Timestamp` type checking in various datetime functions to prevent exceptions when using a subclassed `datetime` (:issue:`25851`)
- Bug in :class:`Series` and :class:`DataFrame` repr where ``np.datetime64('NaT')`` and ``np.timedelta64('NaT')`` with ``dtype=object`` would be represented as ``NaN`` (:issue:`25445`)
- Bug in :class:`BaseExprVisitor` which caused :func:`eval` expressions to fail when named keyword arguments were included within the expression string (:issue:`25813`)
Copy link
Member

Choose a reason for hiding this comment

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

Still needs a little work to make this user facing, i.e. only references items in the documented API (which BaseExprVisitor is not).

Would be better referencing the DataFrame.query method

-
-

Expand Down
5 changes: 1 addition & 4 deletions pandas/core/computation/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,11 +632,8 @@ def visit_Call(self, node, side=None, **kwargs):
if not isinstance(key, ast.keyword):
raise ValueError("keyword error in function call "
"'{func}'".format(func=node.func.id))

if key.arg:
# TODO: bug?
kwargs.append(ast.keyword(
keyword.arg, self.visit(keyword.value))) # noqa
kwargs[key.arg] = self.visit(key.value)()

return self.const_type(res(*new_args, **kwargs), self.env)

Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/computation/test_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1757,6 +1757,29 @@ def test_no_new_globals(self, engine, parser):
assert gbls == gbls2


class TestEvalNamedKWargs(object):
Copy link
Member

Choose a reason for hiding this comment

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

I don't think we need a class here; OK to remove this and put tests at top level of module

# xref https://github.com/pandas-dev/pandas/issues/25813
Copy link
Member

Choose a reason for hiding this comment

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

Just add #GH 25813 to the first line of the tests added here


def test_eval_with_kwargs(self, engine, parser):
def fn(x):
return 2 * x
result = pd.eval("fn(x=2)", engine=engine, parser=parser)
assert result == 4

def test_query_str_contains(self, parser):
df = pd.DataFrame([["I", "XYZ"], ["IJ", None]], columns=['A', 'B'])

expected = df[df["A"].str.contains("J")]
result = df.query("A.str.contains('J')", engine="python",
Copy link
Member

Choose a reason for hiding this comment

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

Any reason to not parametrize this for all engines?

Copy link
Member

@gfyoung gfyoung May 18, 2019

Choose a reason for hiding this comment

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

Yes, because engine=pandas fails for this test (though that should have been explicit).

It's tries to hash a Series object.

parser=parser)
tm.assert_frame_equal(result, expected)

expected = df[df["B"].str.contains("Z", na=False)]
result = df.query("B.str.contains('Z', na=False)", engine="python",
parser=parser)
tm.assert_frame_equal(result, expected)


@td.skip_if_no_ne
def test_invalid_engine():
msg = 'Invalid engine \'asdf\' passed'
Expand Down