w3resource

Pandas - Apply multiple functions to a DataFrame column using apply()

Pandas: Custom Function Exercise-10 with Solution

Write a Pandas function that applies multiple functions to a single column using apply() function.

This exercise demonstrates how to apply multiple functions to a single column in a Pandas DataFrame using apply().

Sample Solution:

Code :

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

# Define two custom functions
def add_one(x):
    return x + 1

def square(x):
    return x ** 2

# Apply both functions to column 'A'
df['A_plus_1'] = df['A'].apply(add_one)
df['A_squared'] = df['A'].apply(square)

# Output the result
print(df)

Output:

   A  B  A_plus_1  A_squared
0  1  4         2          1
1  2  5         3          4
2  3  6         4          9                            

Explanation:

  • Created a DataFrame with columns 'A' and 'B'.
  • Defined two functions: add_one() to increment by 1 and square() to square the values.
  • Applied both functions separately to column 'A' and stored the results in new columns 'A_plus_1' and 'A_squared'.
  • Displayed the updated DataFrame with the new columns.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-apply-multiple-functions-to-a-dataframe-column-using-apply.php