Bird
Raised Fist0
Pandasdata~20 mins

Using appropriate dtypes in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dtype Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of memory usage with different dtypes
What is the output of the following code snippet that compares memory usage of integer columns with default and optimized dtypes?
Pandas
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'A': np.random.randint(0, 100, size=1000),
    'B': np.random.randint(0, 100, size=1000)
})

mem_default = df.memory_usage(deep=True, index=False).sum()
df['A'] = df['A'].astype('int8')
df['B'] = df['B'].astype('int8')
mem_optimized = df.memory_usage(deep=True, index=False).sum()
print(mem_default, mem_optimized)
A16000 2000
B16000 4000
C8000 4000
D8000 2000
Attempts:
2 left
💡 Hint
Think about how changing from default int64 to int8 affects memory size.
❓ data_output
intermediate
2:00remaining
Resulting dtypes after conversion
Given the DataFrame below, what are the dtypes of columns after applying the conversion code?
Pandas
import pandas as pd

df = pd.DataFrame({
    'col1': [1, 2, 3],
    'col2': [0.1, 0.2, 0.3],
    'col3': ['a', 'b', 'c']
})

df['col1'] = df['col1'].astype('int16')
df['col2'] = df['col2'].astype('float32')
Acol1: int16, col2: float32, col3: object
Bcol1: int64, col2: float64, col3: object
Ccol1: int16, col2: float64, col3: string
Dcol1: int32, col2: float32, col3: object
Attempts:
2 left
💡 Hint
Check the astype conversions applied to col1 and col2.
🔧 Debug
advanced
2:00remaining
Identify the error in dtype conversion
What error will this code raise when trying to convert the 'age' column to 'int8'?
Pandas
import pandas as pd

df = pd.DataFrame({'age': [25, 300, 45]})
df['age'] = df['age'].astype('int8')
ATypeError
BValueError
COverflowError
DNo error, conversion succeeds
Attempts:
2 left
💡 Hint
Check if values fit in int8 range (-128 to 127).
🧠 Conceptual
advanced
2:00remaining
Best dtype for categorical data
Which dtype is most memory efficient and appropriate for a column with repeated string categories like 'red', 'blue', 'green'?
Aobject
Bcategory
Cstring
Dint64
Attempts:
2 left
💡 Hint
Think about how pandas stores repeated categories internally.
🚀 Application
expert
3:00remaining
Optimize memory usage for mixed dtype DataFrame
Given a DataFrame with columns: 'id' (integers 0-100000), 'score' (floats 0-1), 'grade' (strings 'A', 'B', 'C'), which dtype conversions will minimize memory usage without losing data?
Aid: int8, score: float32, grade: category
Bid: int16, score: float64, grade: object
Cid: int32, score: float32, grade: category
Did: int64, score: float16, grade: string
Attempts:
2 left
💡 Hint
Consider the range of 'id' and precision needed for 'score'.

Practice

(1/5)
1. Why is it important to use appropriate data types in a pandas DataFrame?
easy
A. It automatically fixes missing data values.
B. It reduces memory usage and speeds up data processing.
C. It makes the DataFrame look colorful in output.
D. It changes the order of rows in the DataFrame.

Solution

  1. Step 1: Understand data types impact on memory

    Using smaller or correct data types reduces the memory needed to store data.
  2. Step 2: Understand data types impact on speed

    Operations on smaller data types run faster, improving performance.
  3. Final Answer:

    It reduces memory usage and speeds up data processing. -> Option B
  4. Quick Check:

    Appropriate dtypes = less memory and faster [OK]
Hint: Smaller data types save memory and speed up work [OK]
Common Mistakes:
  • Thinking data types change data values automatically
  • Believing data types affect DataFrame colors
  • Assuming data types reorder rows
2. Which of the following is the correct way to change a column named age to integer type in pandas?
easy
A. df['age'] = df['age'].astype('int')
B. df.astype('age', int)
C. df['age'].convert(int)
D. df.change_type('age', 'int')

Solution

  1. Step 1: Recall pandas syntax for changing dtype

    The correct method is to use astype() on the column.
  2. Step 2: Check method usage

    Use df['age'] = df['age'].astype('int') to convert the 'age' column to integer.
  3. Final Answer:

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

    astype() method changes dtype [OK]
Hint: df[col] = df[col].astype(dtype) to change dtype [OK]
Common Mistakes:
  • Forgetting to assign the result of astype() back to the column
  • Using non-existent methods like convert() or change_type()
  • Passing arguments in wrong order or syntax
3. Given the code below, what will be the output of df.dtypes?
import pandas as pd
data = {'score': [90, 85, 88], 'passed': ['True', 'False', 'True']}
df = pd.DataFrame(data)
df['passed'] = df['passed'].astype('bool')
print(df.dtypes)
medium
A. score object passed bool dtype: object
B. score int64 passed object dtype: object
C. score int64 passed bool dtype: object
D. score float64 passed bool dtype: object

Solution

  1. Step 1: Check initial data types

    'score' is a list of integers, so pandas infers int64. 'passed' is string initially.
  2. Step 2: Convert 'passed' to boolean

    Using astype('bool') converts 'passed' column to boolean type.
  3. Final Answer:

    score int64 passed bool dtype: object -> Option C
  4. Quick Check:

    astype('bool') converts string to bool [OK]
Hint: astype('bool') converts strings like 'True' to boolean [OK]
Common Mistakes:
  • Assuming 'passed' stays as object after astype('bool')
  • Thinking 'score' becomes float automatically
  • Confusing bool with string type
4. What is wrong with this code snippet?
df['price'] = df['price'].astype('int64')
df['price'] = df['price'].astype('category')
Why might this cause an error or unexpected behavior?
medium
A. Converting numeric to category without checking unique values may increase memory usage or cause unexpected behavior.
B. You cannot convert a column twice in pandas.
C. astype('category') only works on string columns.
D. int64 is not a valid dtype in pandas.

Solution

  1. Step 1: Understand dtype conversion to category

    Converting numeric to category is allowed but categories are based on unique values.
  2. Step 2: Consider memory and behavior risks

    If the numeric column has many unique values, category conversion may increase memory or cause unexpected grouping.
  3. Final Answer:

    Converting numeric to category without checking unique values may increase memory usage or cause unexpected behavior. -> Option A
  4. Quick Check:

    Category dtype needs careful unique value check [OK]
Hint: Check unique values before converting to category [OK]
Common Mistakes:
  • Thinking multiple astype() calls are invalid
  • Believing astype('category') only works on strings
  • Assuming int64 is invalid dtype
5. You have a large DataFrame with a column status containing only three unique string values: 'new', 'in_progress', 'done'. Which dtype change will save memory and keep data efficient?
hard
A. Keep status as string without changes.
B. Convert status to object dtype.
C. Convert status to int64 dtype directly.
D. Convert status to category dtype.

Solution

  1. Step 1: Identify unique values in 'status'

    Only three unique strings exist, ideal for categorical dtype.
  2. Step 2: Understand category dtype benefits

    Category stores unique values once and uses integer codes internally, saving memory.
  3. Step 3: Compare other options

    Object dtype stores full strings repeatedly; int64 conversion is invalid without mapping; no change wastes memory.
  4. Final Answer:

    Convert status to category dtype. -> Option D
  5. Quick Check:

    Few unique strings? Use category dtype [OK]
Hint: Few unique strings? Use category dtype for memory [OK]
Common Mistakes:
  • Trying to convert strings directly to int64 without mapping
  • Keeping object dtype wastes memory
  • Ignoring category dtype benefits
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