user101464
user101464

Reputation: 35

Looping through a list of functions in python:

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.

Upvotes: 0

Views: 65

Answers (1)

Mazhar
Mazhar

Reputation: 1064

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()))

Upvotes: 1

Related Questions