houda benhar
houda benhar

Reputation: 101

Use eval function with 'mean()' and 'median()'

I want to calculate mean and median from of a dataframe so I put them in a list as follows:

comb_methods = ['median','mean']

I use a loop and use eval function to make the functions callable, and calculate the result and add it as a new column to the dataframe

for combin in comb_methods:
 combination = eval(combin)
 heartdata[combin] = heartdata.combination(axis=1)

I get the following error.

name 'median' is not defined

I'm trying to understand why this is occurring for hours but I can't figure it out!

Upvotes: 0

Views: 567

Answers (1)

jfaccioni
jfaccioni

Reputation: 7519

You need to use getattr instead of eval:

for combin in comb_methods:
    heartdata[combin] = getattr(heartdata, combin)(axis=1)

getattr looks for the attribute of a given object with a name as a string. Writing

getattr(heartdata, 'median')

returns heartdata.median (a method which we then call with the axis=1 argument).

eval on the other hand simply evaluates whatever string you pass onto it. So

eval('median')

is the same as simply typing median (without quotes) on a Python script. Python will believe that median is a variable, and will throw the error you see when it can't find said variable.

Upvotes: 2

Related Questions