How to correctly call a class method that has been stored in a separate variable?

Viewed 55

I have a list of processes over dataframes, consisting of functions and methods; and I want to call them in a loop.

For functions I can simply call

function_name(df, **options )

type of function_name here is a function.

For method all works with:

command = 'df.%s( **options )' % method_name
eval( command )

type of process_name here is str.

I've tried to store it like:

method = pd.DataFrame.set_index

function pandas.core.frame.DataFrame.set_index(self, keys, drop=True, append=False, inplace=False, verify_integrity=False)

But calling it afterwards:

df.method( **options )

leads to error:

AttributeError: 'DataFrame' object has no attribute 'method'

I have heard that using eval is bad. What code can replace line with eval above?

1 Answers

Since you're storing the reference for the class method, you could pass df as the first argument along with your options:

method(df, **options)

MinReprex:

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
f = pd.DataFrame.set_index

f(df, 'A', append=True, inplace=True)
df        

     B
  A   
0 1  4
1 2  5
2 3  6
Related