Pandas - Applying Conditional Logic to DataFrame Rows with apply()
12. Conditional Logic with apply() in DataFrame
Write a Pandas program that uses apply() to work with conditional logic in DataFrame.
In this exercise we have applied a custom function that uses conditional logic to set values based on a threshold.
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'A': [10, 20, 30],
'B': [5, 15, 25]
})
# Define a function with conditional logic
def threshold(row):
return 'High' if row['A'] > 15 else 'Low'
# Apply the function to the rows
df['A_threshold'] = df.apply(threshold, axis=1)
# Output the result
print(df)
Output:
A B A_threshold 0 10 5 Low 1 20 15 High 2 30 25 High
Explanation:
- Created a DataFrame with columns 'A' and 'B'.
- Defined a function threshold() that labels 'A' as 'High' if it’s greater than 15, otherwise 'Low'.
- Applied this function row-wise using apply() with axis=1.
- Added the labels as a new column 'A_threshold' in the DataFrame.
For more Practice: Solve these Related Problems:
- Write a Pandas program to use apply() with a custom function that assigns labels to rows based on multiple conditions.
- Write a Pandas program to apply conditional logic to a DataFrame column and return different values based on the condition using apply().
- Write a Pandas program to create a new column by applying a function that uses if-else logic on each row via apply().
- Write a Pandas program to conditionally update values in a DataFrame by applying a lambda function with if-else statements using apply().
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.