The dates are '2023-01-15', '2022-12-31', and '2024-07-04'. Extracting dt.month gets the month numbers: 1, 12, and 7.
Step 2: Convert the extracted months to list
The tolist() method converts the pandas Series to a Python list: [1, 12, 7].
Final Answer:
[1, 12, 7] -> Option A
Quick Check:
Months extracted = [1, 12, 7] [OK]
Hint: dt.month returns month numbers as integers [OK]
Common Mistakes:
Confusing day with month values
Expecting month names instead of numbers
Using dt.day instead of dt.month
4. The following code throws an error. What is the main issue?
import pandas as pd
dates = pd.Series(['2023-01-15', '2022-12-31'])
years = dates.dt.year
print(years)
medium
A. print statement syntax is incorrect
B. dt.year is not a valid attribute
C. dates is not converted to datetime type before using dt accessor
D. dates should be a list, not a pandas Series
Solution
Step 1: Check the data type of dates
The dates Series contains strings, not datetime objects.
Step 2: Understand dt accessor requirements
The dt accessor works only on datetime dtype Series. Without conversion, it raises an error.
Final Answer:
dates is not converted to datetime type before using dt accessor -> Option C
Quick Check:
Convert strings to datetime before dt.year [OK]
Hint: Always convert to datetime before using dt attributes [OK]
Common Mistakes:
Forgetting pd.to_datetime conversion
Assuming dt.year works on string Series
Misreading error as syntax problem
5. You have a DataFrame df with a datetime column 'order_date'. You want to add three new columns: 'year', 'month', and 'day' extracted from 'order_date'. Which code correctly does this?
hard
A. df['year'] = df['order_date'].year
df['month'] = df['order_date'].month
df['day'] = df['order_date'].day
B. df['year'] = df['order_date'].dt.year
df['month'] = df['order_date'].dt.month
df['day'] = df['order_date'].dt.day