Pandas DataFrame ‘eval’ Method.


Pandas DataFrame ‘eval’ Method.

Table Of Contents:

  1. Syntax Of ‘eval( )’ Method In Pandas.
  2. Examples ‘eval( )’ Method.

(1) Syntax:

DataFrame.eval(expr, *, inplace=False, **kwargs)

Description:

  • Evaluate a string describing operations on DataFrame columns.
  • Operates on columns only, not specific rows or elements.
  • This allows eval to run arbitrary code, which can make you vulnerable to code injection if you pass user input to this function.

Parameters:

  • expr: str –
    • The expression string to evaluate.
  • in place: bool, default False –
    • If the expression contains an assignment, whether to perform the operation in place and mutate the existing DataFrame. Otherwise, a new DataFrame is returned.
  • **kwargs –
    • See the documentation for eval() for complete details on the keyword arguments accepted by query().

Returns:

  • ndarray, scalar, pandas object, or None – The result of the evaluation or None if inplace=True

(2) Examples Of ‘eval()’ Method:

Example-1

df = pd.DataFrame({'A': range(1, 6), 'B': range(10, 0, -2)})
df

Output:

# Adding Column ‘A’ and ‘B’.

df.eval('A + B')

Output:

0    11
1    10
2     9
3     8
4     7
dtype: int64

# Creating A New Column Using ‘eval’.

df.eval('C = A + B')

Output:

# Modifying The Original DataFrame.

df.eval('C = A + B', inplace=True)
df

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *