0
0
Pandasdata~5 mins

Extracting year, month, day in Pandas - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A.dt.year
B.dt.month
C.dt.day
D.dt.hour
If a pandas column is not datetime type, what should you do before extracting year, month, or day?
AConvert it using <code>pd.to_datetime()</code>
BUse <code>.astype(int)</code>
CUse <code>.dt.year</code> directly
DDrop the column
What does df['date'].dt.day return?
AThe month number
BThe day of the week as a string
CThe day of the month as an integer
DThe year
Which data type is required for a pandas column to use .dt.year?
Adatetime64[ns]
Bint64
Cobject
Dfloat64
How do you create a new column 'year' from a datetime column 'date' in pandas?
Adf['year'] = df['date'].astype(int)
Bdf['year'] = df['date'].year()
Cdf['year'] = year(df['date'])
Ddf['year'] = df['date'].dt.year
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.