Challenge - 5 Problems
Date Component Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Extract year from a pandas datetime column
Given the DataFrame
df with a datetime column date, what is the output of df['date'].dt.year?Data Analysis Python
import pandas as pd df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-06-01'])}) result = df['date'].dt.year print(result.tolist())
Attempts:
2 left
💡 Hint
Use the
dt accessor to get date parts from pandas datetime columns.✗ Incorrect
The
dt.year extracts the year component from each datetime in the column, returning a Series of years.❓ data_output
intermediate2:00remaining
Extract month and day from datetime
What is the output of extracting month and day from the datetime column
df['date'] using df['date'].dt.month and df['date'].dt.day?Data Analysis Python
import pandas as pd df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2022-12-31', '2024-06-01'])}) months = df['date'].dt.month days = df['date'].dt.day print(months.tolist(), days.tolist())
Attempts:
2 left
💡 Hint
Month and day are separate attributes accessed via
dt.month and dt.day.✗ Incorrect
The
dt.month extracts the month number, and dt.day extracts the day number from each datetime.🔧 Debug
advanced2:00remaining
Identify the error when extracting date components
What error will this code raise?
import pandas as pd
df = pd.DataFrame({'date': ['2023-01-15', '2022-12-31', '2024-06-01']})
years = df['date'].dt.year
print(years.tolist())Attempts:
2 left
💡 Hint
Check the data type of the 'date' column before using
.dt.✗ Incorrect
The 'date' column is string type, not datetime. The
.dt accessor only works on datetime-like data, so it raises AttributeError.🚀 Application
advanced2:30remaining
Create new columns for year, month, and day
Given a DataFrame
df with a datetime column date, which code correctly adds three new columns year, month, and day with the respective date parts?Attempts:
2 left
💡 Hint
Use the
dt accessor and assign each part to a separate column.✗ Incorrect
Option C assigns each date component separately using the
dt accessor, which is the correct way.🧠 Conceptual
expert2:30remaining
Understanding datetime component extraction behavior
If a pandas Series contains some missing datetime values (NaT), what will be the output of extracting the year component using
series.dt.year?Attempts:
2 left
💡 Hint
Consider how pandas handles missing datetime values in numeric extraction.
✗ Incorrect
When extracting year from a datetime Series with missing values, pandas returns a float Series where missing values become NaN because integers cannot represent missing data.