w3resource

Pandas - Applying a Custom Function to Multiple Columns in DataFrame


Pandas: Custom Function Exercise-7 with Solution


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.

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.



Follow us on Facebook and Twitter for latest update.