Bird
Raised Fist0
Data Analysis Pythondata~10 mins

Categorical data type optimization in Data Analysis Python - 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 a categorical type.

Data Analysis Python
df['color'] = df['color'].[1]
Drag options to blanks, or click blank then click option'
Aastype('category')
Bstr
Cto_numeric
Dcopy
Attempts:
3 left
💡 Hint
Common Mistakes
Using to_numeric on a string column causes errors.
Using str() does not change the data type in pandas.
Using copy() just duplicates data without changing type.
2fill in blank
medium

Complete the code to check the memory usage of the DataFrame before optimization.

Data Analysis Python
print(df.memory_usage([1]=True))
Drag options to blanks, or click blank then click option'
Amemory
Bverbose
Cindex
Ddeep
Attempts:
3 left
💡 Hint
Common Mistakes
Using verbose does not affect memory usage calculation.
Using index only shows index memory, not full data.
Using memory is not a valid parameter.
3fill in blank
hard

Fix the error in converting the 'city' column to categorical by filling the blank.

Data Analysis Python
df['city'] = df['city'].[1]('category')
Drag options to blanks, or click blank then click option'
Aastype
Bto_category
Cconvert
Dchange_type
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like convert or to_category.
Trying to use change_type which is not a pandas method.
4fill in blank
hard

Fill both blanks to create a dictionary of category counts for the 'fruit' column.

Data Analysis Python
counts = df['fruit'].[1]().[2]()
Drag options to blanks, or click blank then click option'
Avalue_counts
Bcount
Cto_dict
Dunique
Attempts:
3 left
💡 Hint
Common Mistakes
Using count() instead of value_counts() returns total count, not per category.
Using unique() returns unique values, not counts.
5fill in blank
hard

Fill all three blanks to optimize the 'category' column and check its new memory usage.

Data Analysis Python
df['category'] = df['category'].[1]('category')
mem_after = df.memory_usage([2]=[3]).sum()
Drag options to blanks, or click blank then click option'
Aastype
Bdeep
CTrue
Dcopy
Attempts:
3 left
💡 Hint
Common Mistakes
Using copy instead of astype causes no type change.
Not using deep=True underestimates memory usage.

Practice

(1/5)
1.

What is the main benefit of converting a DataFrame column to category type in pandas?

easy
A. It reduces memory usage by storing unique values once
B. It automatically sorts the column values alphabetically
C. It converts numeric values to strings
D. It removes missing values from the column

Solution

  1. Step 1: Understand what categorical type does

    The categorical type stores unique values only once and uses codes internally, saving memory.
  2. Step 2: Compare with other options

    Sorting, converting to strings, or removing missing values are not automatic effects of categorical conversion.
  3. Final Answer:

    It reduces memory usage by storing unique values once -> Option A
  4. Quick Check:

    Categorical type = Memory saving [OK]
Hint: Categorical stores unique values once to save memory [OK]
Common Mistakes:
  • Thinking it sorts values automatically
  • Confusing with string conversion
  • Assuming it removes missing data
2.

Which of the following is the correct syntax to convert a pandas DataFrame column df['color'] to categorical type?

import pandas as pd
df = pd.DataFrame({'color': ['red', 'blue', 'red', 'green']})
easy
A. df['color'] = df.astype('category')
B. df['color'] = df['color'].astype('category')
C. df['color'] = pd.category(df['color'])
D. df['color'] = df['color'].to_category()

Solution

  1. Step 1: Identify correct method to convert column type

    The astype('category') method converts a Series to categorical type.
  2. Step 2: Check other options for errors

    df['color'] = df.astype('category') tries to convert whole DataFrame, not column. df['color'] = pd.category(df['color']) uses non-existent pd.category(). df['color'] = df['color'].to_category() uses wrong method name.
  3. Final Answer:

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

    astype('category') = Correct syntax [OK]
Hint: Use astype('category') on the specific column [OK]
Common Mistakes:
  • Applying astype to whole DataFrame instead of column
  • Using non-existent pd.category() function
  • Using wrong method like to_category()
3.

What will be the output of the following code?

import pandas as pd

df = pd.DataFrame({'fruit': ['apple', 'banana', 'apple', 'orange', 'banana']})
df['fruit'] = df['fruit'].astype('category')
print(df['fruit'].cat.categories)
medium
A. Index(['apple', 'banana', 'orange'], dtype='object')
B. ['apple', 'banana', 'apple', 'orange', 'banana']
C. ['apple', 'banana', 'orange', 'apple', 'banana']
D. Error: 'cat' attribute not found

Solution

  1. Step 1: Convert column to categorical and check categories

    After conversion, cat.categories shows unique sorted categories.
  2. Step 2: Identify unique values in sorted order

    Unique fruits are 'apple', 'banana', 'orange' in alphabetical order.
  3. Final Answer:

    Index(['apple', 'banana', 'orange'], dtype='object') -> Option A
  4. Quick Check:

    cat.categories = unique sorted values [OK]
Hint: cat.categories shows unique sorted categories [OK]
Common Mistakes:
  • Expecting original list instead of unique categories
  • Confusing categories with values
  • Thinking cat attribute is missing
4.

Identify the error in this code snippet that tries to convert a column to categorical:

import pandas as pd
df = pd.DataFrame({'size': ['S', 'M', 'L', 'M']})
df['size'] = df['size'].astype(category)
medium
A. astype() cannot convert to categorical
B. DataFrame creation syntax is wrong
C. Missing quotes around 'category' in astype()
D. Column 'size' does not exist

Solution

  1. Step 1: Check astype() argument

    The argument to astype() must be a string 'category', not a bare word.
  2. Step 2: Verify other parts of code

    DataFrame creation and column name are correct; astype() supports 'category'.
  3. Final Answer:

    Missing quotes around 'category' in astype() -> Option C
  4. Quick Check:

    Quotes needed for dtype string [OK]
Hint: Always put quotes around dtype names in astype() [OK]
Common Mistakes:
  • Forgetting quotes around 'category'
  • Assuming astype() can't convert to category
  • Mistaking column name errors
5.

You have a DataFrame with a column 'city' containing 1 million rows but only 5 unique city names. Which approach optimizes memory and speeds up grouping by city?

hard
A. Use df.groupby('city') without any conversion
B. Convert 'city' column to string type before grouping
C. Drop duplicates from 'city' column before grouping
D. Convert 'city' column to categorical type before grouping

Solution

  1. Step 1: Understand memory and speed benefits of categorical

    Converting to categorical stores unique values once, reducing memory and speeding grouping.
  2. Step 2: Evaluate other options

    String type uses more memory; dropping duplicates loses data; grouping without conversion is slower.
  3. Final Answer:

    Convert 'city' column to categorical type before grouping -> Option D
  4. Quick Check:

    Categorical = Memory + speed optimization [OK]
Hint: Convert to categorical before grouping large repeated data [OK]
Common Mistakes:
  • Using string type wastes memory
  • Dropping duplicates loses data
  • Grouping without conversion is slower
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