0
0
Pandasdata~20 mins

dtypes for column data types in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Dtype Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this dtype check?
Given the following pandas DataFrame, what will be the output of df.dtypes?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [1.5, 2.5, 3.5],
    'C': ['x', 'y', 'z'],
    'D': [True, False, True]
})
print(df.dtypes)
A
A      int32
B    float64
C     object
D       bool
dtype: object
B
A      float64
B    float64
C     object
D       bool
dtype: object
C
A      int64
B    float64
C     object
D       bool
dtype: object
D
A      int64
B    float64
C     string
D       bool
dtype: object
Attempts:
2 left
💡 Hint
Check the default integer type pandas uses on your system and how strings are stored.
data_output
intermediate
2:00remaining
Count columns with numeric dtypes
Using pandas, how many columns in this DataFrame have numeric data types?
Pandas
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'num1': [1, 2, 3],
    'num2': [1.1, 2.2, 3.3],
    'text': ['a', 'b', 'c'],
    'flag': [True, False, True],
    'date': pd.to_datetime(['2023-01-01', '2023-01-02', '2023-01-03'])
})
numeric_cols = df.select_dtypes(include=[np.number]).columns
print(len(numeric_cols))
A2
B3
C4
D1
Attempts:
2 left
💡 Hint
Numeric types include int and float, but not boolean or datetime.
🔧 Debug
advanced
2:00remaining
Identify the error in dtype conversion
What error will this code raise when trying to convert column 'A' to integer dtype?
Pandas
import pandas as pd

df = pd.DataFrame({'A': ['1', '2', 'three']})
df['A'] = df['A'].astype(int)
AValueError: invalid literal for int() with base 10: 'three'
BTypeError: cannot convert float NaN to integer
CKeyError: 'A'
DNo error, conversion succeeds
Attempts:
2 left
💡 Hint
Check if all strings can be converted to integers.
🚀 Application
advanced
2:00remaining
Select columns with object dtype
Given a DataFrame, which code snippet correctly selects all columns with object dtype?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2],
    'B': ['x', 'y'],
    'C': [3.5, 4.5],
    'D': ['foo', 'bar']
})
Adf.select_dtypes(exclude=['object'])
Bdf.select_dtypes(include=['object'])
Cdf.select_dtypes(include=['int64'])
Ddf.select_dtypes(include=['bool'])
Attempts:
2 left
💡 Hint
Object dtype usually stores strings or mixed types.
🧠 Conceptual
expert
2:00remaining
Understanding pandas dtype memory optimization
Which pandas dtype conversion reduces memory usage the most for a column of integers ranging from 0 to 127?
AConvert to 'object' dtype
BConvert to 'int64' dtype
CConvert to 'float32' dtype
DConvert to 'int8' dtype
Attempts:
2 left
💡 Hint
Consider the smallest integer dtype that can hold values 0 to 127.