Pandas - Apply multiple functions to a DataFrame column using apply()
10. Apply Multiple Functions to a Single Column Using apply()
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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to apply both the mean and standard deviation functions to a single column using apply() with a list of functions.
- Write a Pandas program to compute and display multiple aggregations on a column by applying a custom function that returns several metrics.
- Write a Pandas program to use apply() to perform two separate calculations on one column and merge the results into a new DataFrame.
- Write a Pandas program to apply a lambda function that outputs a tuple of computed values (e.g., min, max) for a given column.
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.