0

The following code works perfectly for function df.max(axis=1) as shown below. Please see Passing a function method into a class in python: for background.

import pandas as pd
df = pd.DataFrame( {'col1': [1, 2], 'col2': [4, 6]})

class our_class():
    def __init__(self, df):
        self.df = df
    
    def arb_func(self, func):
        return func(self.df)

ob1 = our_class(df)
print(ob1.arb_func(lambda x: x.max(axis=1)))

I would like to generalize this by looping through a list of functions. My attempt below fails:

func_list = [max(axis=1), min(axis=0), mean()]

for f in func_list:
      print(ob1.arb_func(lambda x: x.f))

Any comments or suggestions appreciated.

user101464
  • 35
  • 7
  • 1
    I believe you put function calls into a list, not functions. You could use `lambda` as you have shown, you could use `exec` but I don't recommend that, or you could store function names and their arguments together in a compound data structure. – Cresht Jan 28 '22 at 07:31

1 Answers1

1

Here axis 1 means row wise

import pandas as pd
df = pd.DataFrame( {'col1': [1, 2], 'col2': [4, 6]})

class our_class():
    def __init__(self, df):
        self.df = df
    
    def arb_func(self, func):
        return self.df.apply(func,axis=1)

ob1 = our_class(df)
print(ob1.arb_func(lambda x: x.max()))
Mazhar
  • 1,044
  • 6
  • 11
  • Thanks for the comment. Can you please also comment on how I can loop through different functions with your method? – user101464 Jan 28 '22 at 15:40