Andrey Mazur
Andrey Mazur

Reputation: 570

Calculating a formula with pandas objects

I am facing a following problem. I have a DataFrame

my_df = pd.DataFrame({'a.b': [1, 2, 3], 'c': [5, 6, 7], 'd': [8, 9, 10]})

I am reading the following string from a config data

some_text = "-a.b + c - d"

is there a possibility to calculate the formula in some_text variable using Series from my_df(df column) as arguments?

Upvotes: 0

Views: 81

Answers (1)

Space Impact
Space Impact

Reputation: 13255

Use pd.eval but you need to change the column names:

my_df.columns=my_df.columns.str.replace('.','_')
my_df.eval(some_text.replace('.','_'))
0   -4
1   -5
2   -6
dtype: int64

Upvotes: 3

Related Questions