How to Extract Month and Year from Date String in a Pandas DataFrame
Suppose we have a Date
column in my Pandas DataFrame.
Date Num
1950-01-01 1.50
1950-02-01 1.50
1950-03-01 1.50
1950-04-01 1.50
Let’s say we want to create a Year
and Month
column from Date
, but it’s a string.
Convert Date string using DateTimeIndex
We can store the values in our Date
column with DateTimeIndex
, which is simply a collection of timestamp objects with varying UTC offsets.
date = pd.DatetimeIndex(df['Date'])
Extract month and year
We can then extract the month and year (or day or whatever attributes we want) from this DateTimeIndex
.
df['Year'] = date.year
df['Month'] = date.month
Convert Date string using Series.dt
Instead of using pd.DateTimeIndex
, we can simply use .dt
on any datetimelike column.
date = df['Date'].dt
Extract month and year
Extracting the month and year would be the same as with the DateTimeIndex
.
df['Year'] = date.year
df['Month'] = date.month