Categories
Python Answers

How to dynamically evaluate an expression from a formula in Python Pandas?

Spread the love

Sometimes, we want to dynamically evaluate an expression from a formula in Python Pandas.

In this article, we’ll look at how to dynamically evaluate an expression from a formula in Python Pandas.

How to dynamically evaluate an expression from a formula in Python Pandas?

To dynamically evaluate an expression from a formula in Python Pandas, we can use eval.

For instance, we write

np.random.seed(0)
df1 = pd.DataFrame(np.random.choice(10, (5, 4)), columns=list('ABCD'))
df2 = pd.DataFrame(np.random.choice(10, (5, 4)), columns=list('ABCD'))
df3 = pd.DataFrame(np.random.choice(10, (5, 4)), columns=list('ABCD'))
df4 = pd.DataFrame(np.random.choice(10, (5, 4)), columns=list('ABCD'))
x = 5
pd.eval("df1.A + (df1.B * x)")

to create a few datadrames with DataFrame.

Then we call eval with an expression string that gets the values from the dataframes and multiply df1.B by x.

Conclusion

To dynamically evaluate an expression from a formula in Python Pandas, we can use eval.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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