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
.