Recall & Review
beginner
How do you extract the year from a pandas datetime column?
Use the
.dt.year attribute on the datetime column. For example, df['date'].dt.year gives the year part of each date.Click to reveal answer
beginner
What pandas attribute extracts the month from a datetime column?
The
.dt.month attribute extracts the month as an integer (1 to 12) from a datetime column.Click to reveal answer
beginner
How can you get the day of the month from a pandas datetime column?
Use
.dt.day on the datetime column to get the day number (1 to 31) for each date.Click to reveal answer
intermediate
What type should a pandas column be to use
.dt.year, .dt.month, or .dt.day?The column must be of datetime type, like
datetime64[ns]. If not, convert it using pd.to_datetime().Click to reveal answer
beginner
Write a pandas code snippet to create separate columns for year, month, and day from a 'date' column.
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
Click to reveal answer
Which pandas attribute extracts the month from a datetime column?
✗ Incorrect
The
.dt.month attribute extracts the month number from a datetime column.If a pandas column is not datetime type, what should you do before extracting year, month, or day?
✗ Incorrect
You must convert the column to datetime type using
pd.to_datetime() before using .dt attributes.What does
df['date'].dt.day return?✗ Incorrect
.dt.day returns the day number (1 to 31) from each date.Which data type is required for a pandas column to use
.dt.year?✗ Incorrect
The column must be datetime type like
datetime64[ns] to use .dt.year.How do you create a new column 'year' from a datetime column 'date' in pandas?
✗ Incorrect
Use
df['date'].dt.year to extract the year and assign it to a new column.Explain how to extract year, month, and day from a pandas datetime column and why the column type matters.
Think about the .dt accessor and data types.
You got /3 concepts.
Write a short pandas code snippet to add three new columns for year, month, and day from a 'date' column.
Use the .dt accessor on the 'date' column.
You got /3 concepts.