Skip to content

Add a New form of using pd.eval() #59151

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 3 commits into from
Closed
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
30 changes: 27 additions & 3 deletions pandas/core/computation/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def _preparse(
f=_compose(
_replace_locals, _replace_booleans, _rewrite_assign, clean_backtick_quoted_toks
),
) -> str:
) -> (str, str):
"""
Compose a collection of tokenization functions.

Expand All @@ -167,7 +167,13 @@ def _preparse(
the ``tokenize`` module and ``tokval`` is a string.
"""
assert callable(f), "f must be callable"
return tokenize.untokenize(f(x) for x in tokenize_string(source))
tokens = [x for x in tokenize_string(source)]
assigner = None
for i in tokens:
if i[0] == 100:
assigner = i[1]
break
return tokenize.untokenize(f(x) for x in tokens), assigner


def _is_type(t):
Expand Down Expand Up @@ -339,6 +345,18 @@ def f(cls):
return f


def set_original_assigner(node, assigner):
if assigner is None:
return
if node.body is not None and len(node.body) > 0:
for el in node.body:
if isinstance(el, ast.Assign) and el.targets is not None and len(el.targets) > 0:
for tar in el.targets:
if isinstance(tar, ast.Name):
tar.id = assigner
return


@disallow(_unsupported_nodes)
@add_ops(_op_classes)
class BaseExprVisitor(ast.NodeVisitor):
Expand Down Expand Up @@ -403,9 +421,15 @@ def __init__(self, env, engine, parser, preparser=_preparse) -> None:

def visit(self, node, **kwargs):
if isinstance(node, str):
clean = self.preparser(node)
is_pandas_visitor = isinstance(self, PandasExprVisitor)
if is_pandas_visitor:
clean, assigner = self.preparser(node)
else:
clean = self.preparser(node)
try:
node = ast.fix_missing_locations(ast.parse(clean))
if is_pandas_visitor:
set_original_assigner(node, assigner)
except SyntaxError as e:
if any(iskeyword(x) for x in clean.split()):
e.msg = "Python keyword not valid identifier in numexpr query"
Expand Down
Loading