Complete the code to create a categorical column from a list of colors.
import pandas as pd colors = ['red', 'blue', 'green', 'blue', 'red'] cat_colors = pd.Categorical([1]) print(cat_colors)
We pass the list colors directly to pd.Categorical() to create a categorical object.
Complete the code to get the category codes from the categorical data.
import pandas as pd colors = pd.Categorical(['red', 'blue', 'green', 'blue', 'red']) codes = colors.[1] print(codes)
labels which is deprecated.categories which returns category names, not codes.The codes attribute gives the integer codes for each category in the categorical data.
Fix the error in the code to print the category labels of the categorical data.
import pandas as pd colors = pd.Categorical(['red', 'blue', 'green', 'blue', 'red']) print(colors.[1])
labels which is deprecated and causes error.codes which returns integers, not labels.The categories attribute returns the category labels (names) of the categorical data.
Fill both blanks to create a categorical from a list and print its codes.
import pandas as pd fruits = ['apple', 'banana', 'apple', 'orange'] cat_fruits = pd.Categorical([1]) print(cat_fruits.[2])
categories instead of codes for the second blank.pd.Categorical().We create a categorical from the list fruits and then print its integer codes using codes.
Fill all three blanks to create a categorical with custom categories and print codes and categories.
import pandas as pd animals = ['cat', 'dog', 'bird', 'dog', 'cat'] cat_animals = pd.Categorical([1], categories=[2], ordered=True) print(cat_animals.[3]) print(cat_animals.categories)
categories twice instead of codes and categories.We create a categorical from animals with custom ordered categories ['dog', 'cat', 'bird']. Then we print the codes and categories.