0
0
Pandasdata~10 mins

Adding and removing categories in Pandas - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a new category 'D' to the categorical column.

Pandas
import pandas as pd
cats = pd.Categorical(['A', 'B', 'A', 'C'])
cats = cats.add_categories([1])
Drag options to blanks, or click blank then click option'
A'D'
BD
C['D']
D"D"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the category name.
Passing a list instead of a single string when adding one category.
2fill in blank
medium

Complete the code to remove the category 'B' from the categorical column.

Pandas
import pandas as pd
cats = pd.Categorical(['A', 'B', 'A', 'C'], categories=['A', 'B', 'C'])
cats = cats.remove_categories([1])
Drag options to blanks, or click blank then click option'
A"B"
B'B'
CB
D['B']
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the category without quotes.
Passing a list instead of a single string.
3fill in blank
hard

Fix the error in the code to add multiple categories 'D' and 'E' to the categorical column.

Pandas
import pandas as pd
cats = pd.Categorical(['A', 'B', 'A', 'C'])
cats = cats.add_categories([1])
Drag options to blanks, or click blank then click option'
A'D', 'E'
B('D', 'E')
C['D', 'E']
D'D E'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing categories as a single string with spaces.
Passing multiple strings without a list.
4fill in blank
hard

Fill both blanks to create a categorical column with categories 'A', 'B', 'C', then remove 'B'.

Pandas
import pandas as pd
cats = pd.Categorical(['A', 'B', 'C'], categories=[1])
cats = cats.remove_categories([2])
Drag options to blanks, or click blank then click option'
A['A', 'B', 'C']
B'B'
C['B']
D'C'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing categories as a string instead of a list.
Removing category by passing a list instead of a string.
5fill in blank
hard

Fill all three blanks to add categories 'D' and 'E', then remove 'A' from the categorical column.

Pandas
import pandas as pd
cats = pd.Categorical(['A', 'B', 'C'], categories=[1])
cats = cats.add_categories([2])
cats = cats.remove_categories([3])
Drag options to blanks, or click blank then click option'
A['A', 'B', 'C']
B['D', 'E']
C'A'
D'B'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing strings instead of lists for categories or added categories.
Removing category by passing a list instead of a string.