w3resource

Pandas - Conditionally Applying a Function to DataFrame Rows with apply()


8. Conditionally Apply a Function to DataFrame Rows

Write a Pandas program that conditionally apply a function to a DataFrame rows.

This exercise demonstrates how to apply a custom function to rows based on a 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 adds columns A and B if a condition is met
def add_if_condition(row):
    return row['A'] + row['B'] if row['C'] > 150 else row['A']

# Apply the custom function row-wise
df['Conditional_Sum'] = df.apply(add_if_condition, axis=1)

# Output the result
print(df)

Output:

   A   B    C  Conditional_Sum
0  1  10  100                1
1  2  20  200               22
2  3  30  300               33                             

Explanation:

  • Created a DataFrame with columns 'A', 'B', and 'C'.
  • Defined a custom function add_if_condition() that adds columns 'A' and 'B' if column 'C' is greater than 150.
  • Applied the function row-wise using apply() with axis=1.
  • Added the result as a new column 'Conditional_Sum' to the DataFrame.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to conditionally apply a function to rows where a specific column exceeds a threshold.
  • Write a Pandas program to use apply() with a conditional statement that modifies rows only if they meet certain criteria.
  • Write a Pandas program to create a new column by applying a function conditionally on rows based on multiple column values.
  • Write a Pandas program to update rows using apply() only for rows that satisfy a specific condition, leaving others unchanged.

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.