Hint: Extracted year/month/day are integers, not strings [OK]
Common Mistakes:
Expecting strings instead of integers
Mixing order of day, month, year
Forgetting to convert to datetime first
4. What is wrong with this code snippet?
df['year'] = df['date'].year
Assuming df['date'] is a datetime column.
medium
A. You need to use df.year() instead
B. The column must be converted to string first
C. The code will work fine as is
D. It should be df['date'].dt.year to access year
Solution
Step 1: Understand pandas datetime access
Datetime columns require the .dt accessor to extract parts like year.
Step 2: Identify missing .dt accessor
The code misses .dt, so df['date'].year will raise an error or not work as expected.
Final Answer:
It should be df['date'].dt.year to access year -> Option D
Quick Check:
Use .dt before year/month/day [OK]
Hint: Always use .dt before year/month/day on datetime columns [OK]
Common Mistakes:
Omitting .dt accessor
Trying to call year() as a method
Converting datetime to string unnecessarily
5. You have a DataFrame df with a column 'timestamp' containing mixed string dates and some missing values (NaN). You want to create three new columns: 'year', 'month', and 'day'. Which approach correctly handles conversion and extraction without errors?
hard
A. df['year'] = df['timestamp'].dt.year; df['month'] = df['timestamp'].dt.month; df['day'] = df['timestamp'].dt.day