File size: 7,239 Bytes
545ed55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# pandas.eval#

Source: https://pandas.pydata.org/pandas-docs/version/3.0/reference/api/pandas.eval.html
Version: 3.0

pandas.eval(*expr*, *parser='pandas'*, *engine=None*, *local\_dict=None*, *global\_dict=None*, *resolvers=()*, *level=0*, *target=None*, *inplace=False*)[[source]](https://github.com/pandas-dev/pandas/blob/v3.0.0/pandas/core/computation/eval.py#L178-L454)[#](#pandas.eval "Link to this definition")
:   Evaluate a Python expression as a string using various backends.

    Warning

    This function can run arbitrary code which can make you vulnerable to code
    injection if you pass user input to this function.

    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).

            By default, with the numexpr engine, the following operations are supported:

            * Arithmetic operations: `+`, `-`, `*`, `/`, `**`, `%`
            * Boolean operations: `|` (or), `&` (and), and `~` (not)
            * Comparison operators: `<`, `<=`, `==`, `!=`, `>=`, `>`

            Furthermore, the following mathematical functions are supported:

            * Trigonometric: `sin`, `cos`, `tan`, `arcsin`, `arccos`, `arctan`, `arctan2`, `sinh`, `cosh`, `tanh`, `arcsinh`, `arccosh` and `arctanh`
            * Logarithms: `log` natural, `log10` base 10, `log1p` log(1+x)
            * Absolute Value `abs`
            * Square root `sqrt`
            * Exponential `exp` and Exponential minus one `expm1`

            See the numexpr engine [documentation](https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions)
            for further function support details.

            Using the `'python'` engine allows the use of native Python operators
            such as floor division `//`, in addition to built-in and user-defined
            Python functions.

            Additionally, the `'pandas'` parser allows the use of [`and`](https://docs.python.org/3/reference/expressions.html#and "(in Python v3.14)"),
            [`or`](https://docs.python.org/3/reference/expressions.html#or "(in Python v3.14)"), and [`not`](https://docs.python.org/3/reference/expressions.html#not "(in Python v3.14)") with the same semantics as the
            corresponding bitwise operators.

        **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
            [enhancing performance](../../user_guide/enhancingperf.html#enhancingperf-eval) documentation for
            more details.

        **engine**{‘python’, ‘numexpr’}, optional, default None
        :   The engine used to evaluate the expression. Supported engines are

            * None : tries to use `numexpr`, falls back to `python`
            * `'numexpr'` : This is the default engine when `numexpr` is installed.
              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
            [`query()`](pandas.DataFrame.query.html#pandas.DataFrame.query "pandas.DataFrame.query") method to inject the
            `DataFrame.index` and `DataFrame.columns`
            variables that refer to their respective [`DataFrame`](pandas.DataFrame.html#pandas.DataFrame "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`](pandas.DataFrame.query.html#pandas.DataFrame.query "pandas.DataFrame.query")
    :   Evaluates a boolean expression to query the columns of a frame.

    [`DataFrame.eval`](pandas.DataFrame.eval.html#pandas.DataFrame.eval "pandas.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 [enhancing performance](../../user_guide/enhancingperf.html#enhancingperf-eval) documentation for
    more details.

    Examples

    ```None
    >>> 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`:

    ```None
    >>> pd.eval("double_age = df.age * 2", target=df)
      animal  age  double_age
    0    dog   10          20
    1    pig   20          40
    ```