Skip to content

BUG: query modifies the frame when you compare with = #8828

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
15 changes: 14 additions & 1 deletion pandas/computation/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,7 @@ def visitor(x, y):

_python_not_supported = frozenset(['Dict', 'Call', 'BoolOp', 'In', 'NotIn'])
_numexpr_supported_calls = frozenset(_reductions + _mathops)
_query_not_supported = frozenset(['Assign'])


@disallow((_unsupported_nodes | _python_not_supported) -
Expand All @@ -602,6 +603,17 @@ def __init__(self, env, engine, parser,
super(PandasExprVisitor, self).__init__(env, engine, parser, preparser)


@disallow((_unsupported_nodes | _python_not_supported | _query_not_supported) -
(_boolop_nodes | frozenset(['BoolOp', 'Attribute', 'In', 'NotIn',
'Tuple'])))
class PandasQueryExprVisitor(BaseExprVisitor):

def __init__(self, env, engine, parser,
preparser=partial(_preparse, f=compose(_replace_locals,
_replace_booleans))):
super(PandasQueryExprVisitor, self).__init__(env, engine, parser, preparser)


@disallow(_unsupported_nodes | _python_not_supported | frozenset(['Not']))
class PythonExprVisitor(BaseExprVisitor):

Expand Down Expand Up @@ -659,4 +671,5 @@ def names(self):
return frozenset(term.name for term in com.flatten(self.terms))


_parsers = {'python': PythonExprVisitor, 'pandas': PandasExprVisitor}
_parsers = {'python': PythonExprVisitor, 'pandas': PandasExprVisitor,
'pandas_query': PandasQueryExprVisitor}
1 change: 1 addition & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1935,6 +1935,7 @@ def query(self, expr, **kwargs):
>>> df[df.a > df.b] # same result as the previous expression
"""
kwargs['level'] = kwargs.pop('level', 0) + 1
kwargs['parser'] = kwargs.pop('parser', 'pandas_query')
res = self.eval(expr, **kwargs)

try:
Expand Down
12 changes: 11 additions & 1 deletion pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -15210,7 +15210,7 @@ class TestDataFrameQueryPythonPandas(TestDataFrameQueryNumExprPandas):
def setUpClass(cls):
super(TestDataFrameQueryPythonPandas, cls).setUpClass()
cls.engine = 'python'
cls.parser = 'pandas'
cls.parser = 'pandas_query'
cls.frame = _frame.copy()

def test_query_builtin(self):
Expand All @@ -15225,6 +15225,16 @@ def test_query_builtin(self):
result = df.query('sin > 5', engine=engine, parser=parser)
tm.assert_frame_equal(expected, result)

def test_query_with_assign_statement(self):
df = DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c']})
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add the issue number as a comment here

a_before = df['a'].copy()
self.assertRaisesRegexp(
NotImplementedError, "'Assign' nodes are not implemented",
Copy link
Member

Choose a reason for hiding this comment

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

Not a big deal (and you don't need to fix it here), but in an ideal world this should be something closer to SyntaxError, rather than NotImplementedError. NotImplementedError is really for abstract methods that should be overridden in a subclass or for features that genuinely have not been implemented yet. This is different: if = ever works in query it would be a bug.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

NotImplementedError is what you currently get when you do unsupported operations within a query/eval and hit an unsupported node, e.g.:

import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c']})
df.eval("{'x': 1}")
NotImplementedError 
/home/me/.local/lib/python2.7/site-packages/pandas/computation/expr.pyc in visit(self, node, **kwargs)
    312         method = 'visit_' + node.__class__.__name__
    313         visitor = getattr(self, method)
--> 314         return visitor(node, **kwargs)
    315 
    316     def visit_Module(self, node, **kwargs):

/home/me/.local/lib/python2.7/site-packages/pandas/computation/expr.pyc in f(self, *args, **kwargs)
    203     def f(self, *args, **kwargs):
    204         raise NotImplementedError("{0!r} nodes are not "
--> 205                                   "implemented".format(node_name))
    206     return f
    207 
NotImplementedError: 'Dict' nodes are not implemented

So at the moment it's just working like any other invalid query/eval. For this specific case I'll probably try to catch the exception within DataFrame.query() and spit out a more meaningful
message. Not sure where you'd have to intercept the exception if you wanted to raise more
meaningful error messages from eval more generally.

Copy link
Contributor

Choose a reason for hiding this comment

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

the NotImplementedError is fine. I agree ideally should be SyntaxError but that's a separate change (welcome to make an issue if so desired)

df.query, 'a=1', engine=self.engine, parser=self.parser
)
a_after = df['a'].copy()
assert_series_equal(a_before, a_after)


class TestDataFrameQueryPythonPython(TestDataFrameQueryNumExprPython):

Expand Down