Created
April 23, 2020 19:40
-
-
Save shane-edmonds/3008e4c4831180bd72fa1fcb14645e99 to your computer and use it in GitHub Desktop.
Pandas DataFrame Date Splitting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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