Easily organize your functions and apply them

Easily organize your functions and apply them.

In Python, a function is a group of related statements that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable.

Code sample

# libs
import pandas as pd

# functions
def func_1(df=None):
    df['text'] = df['text'].str.replace('3','e')
    return df

def func_2(df=None):
    df['text'] = df['text'].str.strip()
    return df

## Method 1
# dataframe
df= pd.DataFrame({'text':["It is a b3autiful day today   ",
                         "  This movi3 is t3rribl3"]})

df1 = func_1(df)
df1 = func_2(df1)

## Method 2
df = pd.DataFrame({'text':["It is a b3autiful day today   ",
                         "  This movi3 is t3rribl3"]})

df2 = (df.pipe(func_1)
         .pipe(func_2)
)

Leave a Reply