w3resource

Pandas - Apply Custom Function with Multiple Conditions in a DataFrame


14. Create New Column Based on Multiple Conditions Using apply()

Write a Pandas program that uses apply() function to create a new column based on multiple conditions.

This exercise demonstrates how to apply a custom function with multiple conditions to create a new column in a DataFrame.

Sample Solution :

Code :

import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
    'A': [10, 15, 30],
    'B': [20, 25, 10]
})

# Define a function with multiple conditions
def categorize(row):
    if row['A'] > 20 and row['B'] > 20:
        return 'High-High'
    elif row['A'] > 20:
        return 'High-Low'
    elif row['B'] > 20:
        return 'Low-High'
    else:
        return 'Low-Low'

# Apply the function row-wise to create a new category column
df['Category'] = df.apply(categorize, axis=1)

# Output the result
print(df)

Output:

    A   B  Category
0  10  20   Low-Low
1  15  25  Low-High
2  30  10  High-Low                                   

Explanation:

  • Created a DataFrame with columns 'A' and 'B'.
  • Defined a function categorize() that checks multiple conditions based on the values in columns 'A' and 'B'.
  • Applied the function row-wise using apply() with axis=1.
  • Created a new column 'Category' containing labels based on the conditions.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to create a new column that categorizes rows based on conditions across two columns using apply().
  • Write a Pandas program to use apply() to combine values from multiple columns into a new column based on conditional logic.
  • Write a Pandas program to add a column that flags rows as 'High' or 'Low' based on conditions applied to two different columns using apply().
  • Write a Pandas program to create a new column by applying a function that returns different text labels depending on multiple column values.

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.