Challenge - 5 Problems
Categorical Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of adding a new category to a pandas Categorical
What is the output of this code snippet?
Pandas
import pandas as pd cat = pd.Categorical(['apple', 'banana'], categories=['apple', 'banana']) cat = cat.add_categories(['cherry']) print(cat.categories.tolist())
Attempts:
2 left
💡 Hint
Think about what add_categories does to the categories list.
✗ Incorrect
The add_categories method adds new categories to the existing categories without changing the current values. So the categories list will include the original plus the new one.
❓ data_output
intermediate2:00remaining
Result of removing a category from a pandas Categorical
What is the output of this code?
Pandas
import pandas as pd cat = pd.Categorical(['apple', 'banana', 'cherry'], categories=['apple', 'banana', 'cherry']) cat = cat.remove_categories(['banana']) print(cat.categories.tolist())
Attempts:
2 left
💡 Hint
Removing a category deletes it from the categories list.
✗ Incorrect
The remove_categories method removes the specified categories from the categories list. So 'banana' is removed.
🔧 Debug
advanced2:00remaining
Behavior when removing a non-existent category
What happens when running this code?
Pandas
import pandas as pd cat = pd.Categorical(['apple', 'banana'], categories=['apple', 'banana']) cat = cat.remove_categories(['cherry'])
Attempts:
2 left
💡 Hint
remove_categories ignores categories that do not exist.
✗ Incorrect
No error is raised. remove_categories only removes categories present in the current categories list; others are ignored.
🚀 Application
advanced2:00remaining
Effect of removing a category on data values
Given this code, what is the output of the print statement?
Pandas
import pandas as pd cat = pd.Categorical(['apple', 'banana', 'cherry', 'banana'], categories=['apple', 'banana', 'cherry']) cat = cat.remove_categories(['banana']) print(cat.tolist())
Attempts:
2 left
💡 Hint
Removing a category replaces its values with NaN in the data.
✗ Incorrect
When a category is removed, any data values with that category become NaN (missing).
🧠 Conceptual
expert2:00remaining
Why use add_categories instead of directly assigning new categories?
Why is it better to use add_categories to add new categories instead of assigning a new categories list directly?
Attempts:
2 left
💡 Hint
Think about what happens to existing data when categories change.
✗ Incorrect
add_categories safely adds new categories without changing existing data values, preventing errors or data loss.