w3resource

Pandas - Apply Custom Function with Multiple Conditions in a DataFrame

Pandas: Custom Function Exercise-14 with Solution

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.

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-apply-custom-function-with-multiple-conditions-in-dataframe.php