w3resource

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

Pandas: Custom Function Exercise-8 with Solution

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.

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://198.211.115.131/python-exercises/pandas/pandas-conditionally-apply-a-function-to-dataframe-rows-using-apply.php