Extracting just Month and Year separately from Pandas Datetime column
You can extract the month and year separately from a Pandas datetime column using the dt
accessor. Here's an example code snippet:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({'date': ['2022-01-01', '2022-02-01', '2022-03-01']})
# convert the date column to datetime
df['date'] = pd.to_datetime(df['date'])
# extract the month and year separately
df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year
# display the result
print(df)
Watch a video course
Python - The Practical Guide
This will create a new column called 'month' and 'year' with the respective values.