Consider my data-frame to be like this ('x','y','z' are features):

enter image description here

I want to create a python function which will take an expression as a string (something like this: 'x+y-2z') and create a new feature by evaluating the expression. Output should be like:

enter image description here

I want to generalize this function so that it will work for different data-frames with different column(feature) names in the expression.

Edit- I have a prototype of the desired function(named 'parser'):

def parser(exp):

df['new_col'] = df.apply(lambda row: row.x+row.y-2*row.z, axis=1)

However, I want to generalize this part - row.x+row.y-2*row.z so that it will adjust itself according to the string(i.e. expression) provided as its argument.


1 Answer 1


Welcome to the community!

The code below is a starter. You can go on by naming the column and adding it to the original DataFrame:

import pandas as pd

data = pd.DataFrame({'x':[1,2,3], 'y':[10,20,30],'z':[100,200,300]})
def my_fun(data,expression,variables):
    for v in variables:
        expression = expression.replace(v,'data.'+str(v))
    return eval(expression)



   x   y    z
0  1  10  100
1  2  20  200
2  3  30  300

0    12
1    24
2    36
dtype: int64

There are two ways in general:

  1. Use eval function to evaluate/execute expression in string form as I did.
  2. Use symbolic libraries, most commonly used is SymPy, to use symbolics directly as variables.

Hope it helps. Good Luck!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.