Reputation: 3
My dataframe has a column of dates like 2014-11-12. I want to split it into two columns: Year and Month_date and put year as 2014 in 'Year column' and Nov 12 in 'Month_date' column. I have split Date column but not able to put in 'Nov 12' format. I am new to python. Any help will be highly appreciated.
Upvotes: 0
Views: 78
Reputation: 862581
I think you need:
df['Date'] = pd.to_datetime(df['Date'])
df['Year'] = df['Date'].dt.year
df['Month-Date'] = df['Date'].dt.strftime('%m-%d')
print (df)
ID Date Data_Value Year Month-Date
0 USW00094889 2014-11-12 22 2014 11-12
1 USC00208972 2009-04-29 56 2009 04-29
2 USC00200032 2008-05-26 278 2008 05-26
3 USC00205563 2005-11-11 139 2005 11-11
4 USC00200230 2014-02-27 -106 2014 02-27
5 USW00014833 2010-10-01 194 2010 10-01
6 USC00207308 2010-06-29 144 2010 06-29
df['Date'] = pd.to_datetime(df['Date'])
df['Year'] = df['Date'].dt.year
df['Month-Date'] = df['Date'].dt.strftime('%b-%d')
print (df)
ID Date Data_Value Year Month-Date
0 USW00094889 2014-11-12 22 2014 Nov-12
1 USC00208972 2009-04-29 56 2009 Apr-29
2 USC00200032 2008-05-26 278 2008 May-26
3 USC00205563 2005-11-11 139 2005 Nov-11
4 USC00200230 2014-02-27 -106 2014 Feb-27
5 USW00014833 2010-10-01 194 2010 Oct-01
6 USC00207308 2010-06-29 144 2010 Jun-29
Upvotes: 1