zmc
2023-12-22 9fdbf60165db0400c2e8e6be2dc6e88138ac719a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
U
¬ý°d:8ã@sdZddlmZddlZddlmZddlZddlmZddl    m
Z
ddl m Z ddl mZdd    lmZmZdd
lmZdd lmZdd lmZdd lmZer¬ddlmZdddœdd„Zddœdd„Zdd„Zdd„Zddœdd„Z ddddœd d!„Z!d*d%dddd&d'œd(d)„Z"dS)+z
Top level ``eval`` module.
é)Ú annotationsN)Ú TYPE_CHECKING)Úfind_stack_level)Úvalidate_bool_kwarg©Úis_extension_array_dtype)ÚENGINES)ÚPARSERSÚExpr)Útokenize_string)Ú ensure_scope)ÚNDFrame)Ú pprint_thing)ÚBinOpz
str | NoneÚstr)ÚengineÚreturncCslddlm}ddlm}|dkr,|r(dnd}|tkrTtt ¡ƒ}td|›d|›ƒ‚|dkrh|shtd    ƒ‚|S)
a?
    Make sure a valid engine is passed.
 
    Parameters
    ----------
    engine : str
        String to validate.
 
    Raises
    ------
    KeyError
      * If an invalid engine is passed.
    ImportError
      * If numexpr was requested but doesn't exist.
 
    Returns
    -------
    str
        Engine name.
    r)ÚNUMEXPR_INSTALLED)Ú USE_NUMEXPRNÚnumexprÚpythonzInvalid engine 'z' passed, valid engines are z~'numexpr' is not installed or an unsupported version. Cannot use engine='numexpr' for query/eval if 'numexpr' is not installed)    Zpandas.core.computation.checkrZ#pandas.core.computation.expressionsrrÚlistÚkeysÚKeyErrorÚ ImportError)rrrZ valid_engines©rúSd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/computation/eval.pyÚ _check_engines    ÿ ÿr©ÚparsercCs$|tkr td|›dt ¡›ƒ‚dS)z¨
    Make sure a valid parser is passed.
 
    Parameters
    ----------
    parser : str
 
    Raises
    ------
    KeyError
      * If an invalid parser is passed
    zInvalid parser 'z' passed, valid parsers are N)r    rrrrrrÚ _check_parserKs ÿr cCs:|dk    r6|D](}t|dƒs t|ƒj}td|›dƒ‚q dS)NÚ __getitem__zResolver of type 'z+' does not implement the __getitem__ method)ÚhasattrÚtypeÚ__name__Ú    TypeError)Ú    resolversÚresolverÚnamerrrÚ_check_resolvers^s
 
 
ÿr)cCs|s tdƒ‚dS)zæ
    Make sure an expression is not an empty string
 
    Parameters
    ----------
    expr : object
        An object that can be converted to a string
 
    Raises
    ------
    ValueError
      * If expr is an empty string
    zexpr cannot be an empty stringN)Ú
ValueError)ÚexprrrrÚ_check_expressionisr,)rcCst|ƒ}t|ƒ|S)a&
    Convert an object to an expression.
 
    This function converts an object to an expression (a unicode string) and
    checks to make sure it isn't empty after conversion. This is used to
    convert operators to their string representation for recursive calls to
    :func:`~pandas.eval`.
 
    Parameters
    ----------
    expr : object
        The object to be converted to a string.
 
    Returns
    -------
    str
        The string representation of an object.
 
    Raises
    ------
    ValueError
      * If the expression is empty.
    )rr,)r+ÚsrrrÚ_convert_expression{sr.Úint)r+Ú stack_levelrcCsZ|dk}|dk}|rd}n|r"d}|s*|rVt|ƒD]"\}}|tjkr2|dkr2t|ƒ‚q2dS)NrÚpandasz5The '@' prefix is only supported by the pandas parserzuThe '@' prefix is not allowed in top-level eval calls.
please refer to your variables by name without the '@' prefix.ú@)r ÚtokenizeÚOPÚ SyntaxError)r+r0rZat_top_of_stackZnot_pandas_parserÚmsgÚtoknumÚtokvalrrrÚ_check_for_locals˜sÿr9r1rFz str | BinOpÚbool)r+rrÚlevelÚinplacec     Cs®t|dƒ}t|tƒr0t|ƒdd„| ¡Dƒ}    n|g}    t|    ƒdk}
|
rV|dkrVtdƒ‚t|ƒ}t|ƒt    |ƒd} d} d} |    D]}t
|ƒ}t |||ƒt |d||||d    }t ||||d
}|d krt|jjƒst|jd dƒdk    rtd d„|jjDƒƒrtjdttƒdd}t|}||ƒ}| ¡} |jdkrX|
rJtdƒ‚|rXtdƒ‚|j}|jdk    r~|dk    r~d} |sÀ| rÀz|j ¡}Wn.tk
r¼}ztdƒ|‚W5d}~XYnXn|j}zJtjdd4|rüt|tƒrü| |j dd…|f<n| ||<W5QRXWn2t!t"fk
rB}ztdƒ|‚W5d}~XYnX|sV|| if}n2|D]}||krZ| ||<qˆqZ||| if7}d} d} q~|dkrª| r¦|S| SdS)a'
    Evaluate a Python expression as a string using various backends.
 
    The following arithmetic operations are supported: ``+``, ``-``, ``*``,
    ``/``, ``**``, ``%``, ``//`` (python engine only) along with the following
    boolean operations: ``|`` (or), ``&`` (and), and ``~`` (not).
    Additionally, the ``'pandas'`` parser allows the use of :keyword:`and`,
    :keyword:`or`, and :keyword:`not` with the same semantics as the
    corresponding bitwise operators.  :class:`~pandas.Series` and
    :class:`~pandas.DataFrame` objects are supported and behave as they would
    with plain ol' Python evaluation.
 
    Parameters
    ----------
    expr : str
        The expression to evaluate. This string cannot contain any Python
        `statements
        <https://docs.python.org/3/reference/simple_stmts.html#simple-statements>`__,
        only Python `expressions
        <https://docs.python.org/3/reference/simple_stmts.html#expression-statements>`__.
    parser : {'pandas', 'python'}, default 'pandas'
        The parser to use to construct the syntax tree from the expression. The
        default of ``'pandas'`` parses code slightly different than standard
        Python. Alternatively, you can parse an expression using the
        ``'python'`` parser to retain strict Python semantics.  See the
        :ref:`enhancing performance <enhancingperf.eval>` documentation for
        more details.
    engine : {'python', 'numexpr'}, default 'numexpr'
 
        The engine used to evaluate the expression. Supported engines are
 
        - None : tries to use ``numexpr``, falls back to ``python``
        - ``'numexpr'`` : This default engine evaluates pandas objects using
          numexpr for large speed ups in complex expressions with large frames.
        - ``'python'`` : Performs operations as if you had ``eval``'d in top
          level python. This engine is generally not that useful.
 
        More backends may be available in the future.
    local_dict : dict or None, optional
        A dictionary of local variables, taken from locals() by default.
    global_dict : dict or None, optional
        A dictionary of global variables, taken from globals() by default.
    resolvers : list of dict-like or None, optional
        A list of objects implementing the ``__getitem__`` special method that
        you can use to inject an additional collection of namespaces to use for
        variable lookup. For example, this is used in the
        :meth:`~DataFrame.query` method to inject the
        ``DataFrame.index`` and ``DataFrame.columns``
        variables that refer to their respective :class:`~pandas.DataFrame`
        instance attributes.
    level : int, optional
        The number of prior stack frames to traverse and add to the current
        scope. Most users will **not** need to change this parameter.
    target : object, optional, default None
        This is the target object for assignment. It is used when there is
        variable assignment in the expression. If so, then `target` must
        support item assignment with string keys, and if a copy is being
        returned, it must also support `.copy()`.
    inplace : bool, default False
        If `target` is provided, and the expression mutates `target`, whether
        to modify `target` inplace. Otherwise, return a copy of `target` with
        the mutation.
 
    Returns
    -------
    ndarray, numeric scalar, DataFrame, Series, or None
        The completion value of evaluating the given code or None if ``inplace=True``.
 
    Raises
    ------
    ValueError
        There are many instances where such an error can be raised:
 
        - `target=None`, but the expression is multiline.
        - The expression is multiline, but not all them have item assignment.
          An example of such an arrangement is this:
 
          a = b + 1
          a + 2
 
          Here, there are expressions on different lines, making it multiline,
          but the last line has no variable assigned to the output of `a + 2`.
        - `inplace=True`, but the expression is missing item assignment.
        - Item assignment is provided, but the `target` does not support
          string item assignment.
        - Item assignment is provided and `inplace=False`, but the `target`
          does not support the `.copy()` method
 
    See Also
    --------
    DataFrame.query : Evaluates a boolean expression to query the columns
            of a frame.
    DataFrame.eval : Evaluate a string describing operations on
            DataFrame columns.
 
    Notes
    -----
    The ``dtype`` of any objects involved in an arithmetic ``%`` operation are
    recursively cast to ``float64``.
 
    See the :ref:`enhancing performance <enhancingperf.eval>` documentation for
    more details.
 
    Examples
    --------
    >>> df = pd.DataFrame({"animal": ["dog", "pig"], "age": [10, 20]})
    >>> df
      animal  age
    0    dog   10
    1    pig   20
 
    We can add a new column using ``pd.eval``:
 
    >>> pd.eval("double_age = df.age * 2", target=df)
      animal  age  double_age
    0    dog   10          20
    1    pig   20          40
    r<cSs g|]}| ¡dkr| ¡‘qS)Ú)Ústrip)Ú.0ÚerrrÚ
<listcomp>0s zeval.<locals>.<listcomp>éNzPmulti-line expressions are only valid in the context of data, use DataFrame.evalTF)Ú global_dictÚ
local_dictr&Útarget)rrÚenvrÚ operand_typescss|]}t|ƒVqdS)Nr)r?ÚelemrrrÚ    <genexpr>Usÿzeval.<locals>.<genexpr>zƒEngine has switched to 'python' because numexpr does not support extension array dtypes. Please set your engine to python manually.)Ú
stacklevelrzNMulti-line expressions are only valid if all expressions contain an assignmentz0Cannot operate inplace if there is no assignmentz"Cannot return a copy of the target)Úrecordz)Cannot assign expression output to target)#rÚ
isinstancerr,Ú
splitlinesÚlenr*rr r)r.r9r r
rZtermsÚ return_typeÚgetattrÚanyrGÚwarningsÚwarnÚRuntimeWarningrrÚevaluateÚassignerrEÚcopyÚAttributeErrorÚcatch_warningsr Úlocr%Ú
IndexError)r+rrrDrCr&r;rEr<ÚexprsZ
multi_lineÚretZ
first_exprZtarget_modifiedrFZ parsed_exprZengZeng_instrVÚerrr'rrrÚevalªs 
 
  ÿ
 û
 
ÿþþýü ÿ  
 
 
r_)r1NNNrrNF)#Ú__doc__Ú
__future__rr3ÚtypingrrRZpandas.util._exceptionsrZpandas.util._validatorsrZpandas.core.dtypes.commonrZpandas.core.computation.enginesrZpandas.core.computation.exprr    r
Zpandas.core.computation.parsingr Zpandas.core.computation.scoper Zpandas.core.genericr Zpandas.io.formats.printingrZpandas.core.computation.opsrrr r)r,r.r9r_rrrrÚ<module>s<           - ÷