Skip to content

Instantly share code, notes, and snippets.

@shane-edmonds
Created April 23, 2020 19:40
Show Gist options
  • Save shane-edmonds/3008e4c4831180bd72fa1fcb14645e99 to your computer and use it in GitHub Desktop.
Save shane-edmonds/3008e4c4831180bd72fa1fcb14645e99 to your computer and use it in GitHub Desktop.
Pandas DataFrame Date Splitting
#pandas datetimeindex docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html
#efficient way to extract year from string format date
df['year'] = pd.DatetimeIndex(df['birth_date']).year
df.head()
#pandas datetimeindex docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html
df['month'] = pd.DatetimeIndex(df['birth_date']).month
df.head()
#if the date format comes in datetime, we can also extract the day/month/year using the to_period function
#where 'D', 'M', 'Y' are inputs
df['month_year'] = pd.to_datetime(df['birth_date']).dt.to_period('M')
df.head()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment