Alina
Alina

Reputation: 2261

collect multiple functions and apply all of them on a dataframe

I have several functions:

def func1
def func2
def func3

I want to apply all of them in a specific order on a Python dataframe. I could do something like this:

df = func1(df)
df = func2(df)
df = func3(df)

or like:

df = func3(func2(func1(df)))

Is there any more Pythonic way of doing it?

Upvotes: 2

Views: 45

Answers (2)

Babak
Babak

Reputation: 613

put them all in class and make sure they all return the class then chain them:

df = pd.DataFrame([[1,2]])
class foo():
    def __init__(self, df=pd.DataFrame()):
        self.df = df

    def __call__(self, df=pd.DataFrame()):
        return foo(df=df)

    def print(self):
        print("here we go")
        print (self.df)
        return self

    def func1(self):
        self.df=self.df.append([[2,3]])
        return self
    def func2(self):
        self.df=self.df.append([[3,4]])
        return self
    def func3(self):
        self.df=self.df.append([[4,5]])
        return self 


a = foo(df)
a.print().func1().print().func2().print().func3().print()

Upvotes: 1

kindall
kindall

Reputation: 184171

Use a loop:

for f in (func1, func2, func3):
     df = f(df)

Upvotes: 3

Related Questions