0
0
Pandasdata~15 mins

Category codes and labels in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Category codes and labels
📖 Scenario: You work in a small store that tracks product categories. Each product belongs to a category like 'Fruit', 'Vegetable', or 'Dairy'. You want to organize these categories using codes to make analysis easier.
🎯 Goal: Create a pandas DataFrame with product names and categories. Then convert the category column to a categorical type. Finally, extract and print the category codes and labels.
📋 What You'll Learn
Create a pandas DataFrame called products with columns 'Product' and 'Category' using exact data.
Create a categorical version of the 'Category' column called cat_categories.
Extract the category codes into a variable called category_codes.
Extract the category labels into a variable called category_labels.
Print category_codes and category_labels.
💡 Why This Matters
🌍 Real World
Stores and businesses often use category codes to simplify data storage and speed up analysis when working with product categories.
💼 Career
Data analysts and scientists use categorical data types to optimize memory and perform faster grouping and filtering in real datasets.
Progress0 / 4 steps
1
Create the products DataFrame
Create a pandas DataFrame called products with columns 'Product' and 'Category'. Use these exact entries: 'Apple' in 'Fruit', 'Carrot' in 'Vegetable', 'Milk' in 'Dairy', 'Banana' in 'Fruit', and 'Cheese' in 'Dairy'.
Pandas
Need a hint?

Use pd.DataFrame with a dictionary where keys are column names and values are lists of entries.

2
Convert Category column to categorical
Create a categorical version of the 'Category' column from products and assign it to a variable called cat_categories.
Pandas
Need a hint?

Use astype('category') on the 'Category' column.

3
Extract category codes and labels
Extract the category codes from cat_categories into a variable called category_codes. Extract the category labels from cat_categories into a variable called category_labels.
Pandas
Need a hint?

Use .cat.codes for codes and .cat.categories for labels.

4
Print category codes and labels
Print the variables category_codes and category_labels to display the category codes and labels.
Pandas
Need a hint?

Use two print() statements, one for category_codes and one for category_labels.