Bird
Raised Fist0
Pandasdata~10 mins

Converting to categorical in Pandas - Interactive Code Practice

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

Complete the code to convert the 'color' column to categorical type.

Pandas
df['color'] = df['color'].[1]()
Drag options to blanks, or click blank then click option'
Atolist
Bto_numeric
Cstr
Dastype('category')
Attempts:
3 left
💡 Hint
Common Mistakes
Using to_numeric instead of astype('category')
Trying to convert to string instead of categorical
2fill in blank
medium

Complete the code to get the categories of the 'color' column after conversion.

Pandas
categories = df['color'].[1]
Drag options to blanks, or click blank then click option'
Acat.categories
Bunique()
Cvalues
Ddtype
Attempts:
3 left
💡 Hint
Common Mistakes
Using unique() which returns unique values but not categories
Using dtype which returns data type, not categories
3fill in blank
hard

Fix the error in the code to convert 'size' column to categorical with specified order.

Pandas
df['size'] = pd.Categorical(df['size'], categories=[1], ordered=True)
Drag options to blanks, or click blank then click option'
A['small', 'medium', 'large']
B['small', 'large', 'medium']
C['tiny', 'small', 'big']
D['large', 'medium', 'small']
Attempts:
3 left
💡 Hint
Common Mistakes
Using categories in wrong order
Using categories not matching the data
4fill in blank
hard

Fill both blanks to create a new categorical column 'rating_cat' from 'rating' with categories and order.

Pandas
df['rating_cat'] = pd.Categorical(df['rating'], categories=[1], ordered=[2])
Drag options to blanks, or click blank then click option'
A['low', 'medium', 'high']
BTrue
CFalse
D['high', 'medium', 'low']
Attempts:
3 left
💡 Hint
Common Mistakes
Setting ordered to False when order matters
Using categories in wrong order
5fill in blank
hard

Fill all three blanks to create a categorical column 'grade_cat' from 'grade' with categories, order, and rename categories.

Pandas
df['grade_cat'] = pd.Categorical(df['grade'], categories=[1], ordered=[2])
df['grade_cat'] = df['grade_cat'].cat.[3](['Poor', 'Average', 'Good'])
Drag options to blanks, or click blank then click option'
A['C', 'B', 'A']
BTrue
Crename_categories
Dset_categories
Attempts:
3 left
💡 Hint
Common Mistakes
Using rename_categories which is not a pandas method
Not setting ordered=True when order matters

Practice

(1/5)
1. What is the main benefit of converting a text column to a categorical type in pandas?
easy
A. It removes duplicate rows from the DataFrame.
B. It changes the text to numbers automatically.
C. It saves memory and speeds up analysis.
D. It sorts the DataFrame by that column.

Solution

  1. Step 1: Understand what categorical type does

    Converting text to categorical stores repeated values efficiently, saving memory.
  2. Step 2: Recognize impact on analysis speed

    Operations on categorical data are faster because pandas uses codes internally.
  3. Final Answer:

    It saves memory and speeds up analysis. -> Option C
  4. Quick Check:

    Converting to categorical = Save memory and speed [OK]
Hint: Categorical = less memory + faster analysis [OK]
Common Mistakes:
  • Thinking it changes text to numbers visibly
  • Assuming it sorts data automatically
  • Confusing with removing duplicates
2. Which of the following is the correct syntax to convert a pandas DataFrame column df['color'] to categorical?
easy
A. df['color'] = df['color'].astype('category')
B. df['color'] = pd.to_categorical(df['color'])
C. df['color'] = df['color'].convert('category')
D. df['color'] = df['color'].category()

Solution

  1. Step 1: Recall pandas method for type conversion

    The correct method is astype('category') to convert column type.
  2. Step 2: Check each option

    df['color'] = df['color'].astype('category') uses astype('category'), which is correct. Others are invalid pandas syntax.
  3. Final Answer:

    df['color'] = df['color'].astype('category') -> Option A
  4. Quick Check:

    Use astype('category') to convert [OK]
Hint: Use astype('category') to convert columns [OK]
Common Mistakes:
  • Using non-existent methods like convert() or category()
  • Trying pd.to_categorical which is not a pandas function
  • Missing quotes around 'category'
3. Given the code:
import pandas as pd
df = pd.DataFrame({'size': ['S', 'M', 'L', 'M', 'S']})
df['size'] = pd.Categorical(df['size'], categories=['S', 'M', 'L'], ordered=True)
print(df['size'].dtype)

What will be the output?
medium
A. category
B. object
C. string
D. int64

Solution

  1. Step 1: Understand pd.Categorical usage

    Using pd.Categorical converts the column to categorical dtype with order.
  2. Step 2: Check dtype after conversion

    The dtype of the column becomes category, not object or string.
  3. Final Answer:

    category -> Option A
  4. Quick Check:

    pd.Categorical sets dtype to category [OK]
Hint: pd.Categorical sets dtype to category [OK]
Common Mistakes:
  • Expecting dtype to remain object
  • Confusing category with string dtype
  • Thinking dtype becomes int64
4. What is wrong with this code snippet?
import pandas as pd
df = pd.DataFrame({'grade': ['A', 'B', 'C', 'B', 'A']})
df['grade'] = pd.Categorical(df['grade'], categories=['A', 'B', 'C'])
df['grade'] = df['grade'].astype('category', ordered=True)
medium
A. DataFrame column cannot be converted twice.
B. astype() does not accept ordered=True argument.
C. pd.Categorical requires categories to be sorted alphabetically.
D. Missing import statement for pandas.

Solution

  1. Step 1: Check astype() method parameters

    The astype() method does not accept an ordered parameter.
  2. Step 2: Identify correct way to set ordered

    Ordering must be set when creating the categorical with pd.Categorical(..., ordered=True), not via astype.
  3. Final Answer:

    astype() does not accept ordered=True argument. -> Option B
  4. Quick Check:

    ordered=True only in pd.Categorical, not astype [OK]
Hint: ordered=True only works in pd.Categorical, not astype [OK]
Common Mistakes:
  • Trying to set ordered in astype()
  • Assuming categories must be sorted alphabetically
  • Thinking multiple conversions cause error
5. You have a DataFrame df with a column 'status' containing repeated text values: 'low', 'medium', 'high'. You want to convert it to a categorical type with the order low < medium < high, and then get the counts of each category in order. Which code snippet correctly does this?
hard
A. df['status'] = df['status'].astype('category', ordered=True) print(df['status'].value_counts(sort=False))
B. df['status'] = df['status'].astype('category') print(df['status'].value_counts())
C. df['status'] = pd.Categorical(df['status']) print(df['status'].value_counts(sort=True))
D. df['status'] = pd.Categorical(df['status'], categories=['low', 'medium', 'high'], ordered=True) print(df['status'].value_counts(sort=False))

Solution

  1. Step 1: Convert with ordered categories

    Use pd.Categorical with categories=['low', 'medium', 'high'] and ordered=True to set order.
  2. Step 2: Get counts without sorting

    Use value_counts(sort=False) to get counts in category order.
  3. Final Answer:

    df['status'] = pd.Categorical(df['status'], categories=['low', 'medium', 'high'], ordered=True) print(df['status'].value_counts(sort=False)) -> Option D
  4. Quick Check:

    pd.Categorical + ordered + value_counts(sort=False) = correct [OK]
Hint: Use pd.Categorical with ordered and value_counts(sort=False) [OK]
Common Mistakes:
  • Using astype('category') without order
  • Not setting ordered=True for category order
  • Using value_counts() without sort=False loses order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard