Pandas - Applying Conditional Logic to DataFrame Rows with apply()
Pandas: Custom Function Exercise-12 with Solution
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.
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.
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://w3resource.com/python-exercises/pandas/pandas-apply-conditional-logic-to-dataframe-rows-with-apply.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics