Pandas - Applying a Custom Function to Multiple Columns in DataFrame
7. Apply Custom Function to Multiple Columns Using apply()
Write a Pandas program that applies a custom function to multiple columns using apply().
In this exercise, we have applied a custom function to multiple columns of a DataFrame, modifying their values based on a specific condition.
Sample Solution:
Code :
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [10, 20, 30],
'C': [100, 200, 300]
})
# Define a custom function that subtracts a value from two columns
def subtract_values(row):
return row['A'] - row['B']
# Apply the custom function across columns 'A' and 'B' for each row
df['A_minus_B'] = df.apply(subtract_values, axis=1)
# Output the result
print(df)
Output:
A B C A_minus_B 0 1 10 100 -9 1 2 20 200 -18 2 3 30 300 -27
Explanation:
- Created a DataFrame with columns 'A', 'B', and 'C'.
- Defined a custom function subtract_values() that subtracts column 'B' from column 'A'.
- Applied this function across columns using apply() with axis=1.
- Added the results as a new column 'A_minus_B' in the DataFrame.
For more Practice: Solve these Related Problems:
- Write a Pandas program to apply a custom function on multiple columns that calculates a weighted sum and returns the result as a new column.
- Write a Pandas program to use apply() to combine two or more columns into a single formatted string.
- Write a Pandas program to apply a custom function to multiple columns that returns the difference between the maximum and minimum values across those columns.
- Write a Pandas program to create a new column by applying a custom function that uses values from two columns to compute a ratio.
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.