Pandas DataFrame eval() method with examples

Spread the love

The eval() method in pandas uses string expressions to efficiently compute operations on a dataframe.

Syntax –

dataframe.eval(expr, inplace, kwargs) 

expr – The expression string to evaluate.

inplace – whether to perform the operation inplace and mutate the existing DataFrame. Otherwise, a new DataFrame is returned.

Examples –

Let’s create a DataFrame to work with.

import pandas as pd

df = pd.DataFrame({'A':[1, 2, 3, 4, 5],
                  'B': [6, 7, 8, 9, 10]})
df

Let’s say that you want to add the columns A and B together and create a new column C. One way to do that is

df['C'] = df['A'] + df['B']

You can do the same operation using the eval() method like this –

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

Multiple columns can be assigned to using multi-line expressions.

df.eval(
    """
    C = A + B
    D = A - B
    """
)

Rating: 1 out of 5.

Leave a Reply