How to Apply a Function to Multiple columns in Pandas?

Spread the love

Applying a Function to Multiple Columns in Pandas –

Before we begin let’s create a pandas DataFrame to work with.

import pandas as pd

data = {'Monday': [120, 20, 80],
       'Tuesday':[125, 20, 85],
       'Wednesday':[125, 25, 85],
       'Thursday':[120, 25, 80],
       'Friday':[120, 30, 90],
       'Saturday':[150, 35, 100],
       'Sunday':[150, 35, 100]}

df = pd.DataFrame(data, index=['Apple','Banana','Mango'])

Here we have weekly prices of fruits.

Using apply() to apply function to multiple columns –

To apply functions to multiple columns in pandas we can use the apply() method.

Let’s say I want to increase the prices by 20 to make more profit. I can write a function for that and apply to the whole dataframe.

def increase_prices(x):
    return x + 20

df1 = df.apply(increase_prices, axis=1)

We can see that all the prices has been increased by 20. We use axis=1 to apply the function to columns, for rows we use axis=0.

Now let’s say that I want to add the Saturday and Sunday prices. To do that we can write a function then apply it to the dataframe.

def sat_sun(x):
    return x['Saturday'] + x['Sunday']

df1['sat_sun'] = df1.apply(sat_sun, axis=1)

I can do the same using the lambda function.

df1['sat_sun_new'] = df1.apply(lambda x: x['Saturday'] + x['Sunday'], axis=1)

Rating: 1 out of 5.

Leave a Reply