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.
Asked
Active
Viewed 71 times
0
-
using `df.Date.dt.month`, and build a dict like`{1:'Jan',2:'Feb'...}` athen using `map` – BENY Sep 01 '17 at 04:36
-
This may be a repeated question & answer here: https://stackoverflow.com/questions/6557553/get-month-name-from-number ... It would help also if you provided some of your code... If you are asking what I think, you have 2 options as far as I know: **(1)** Use full name of month, which would require you to import `datetime` and use `.strftime('%B')`. **(2)** Use abbreviations. In this case you should create your own system using an array. Basically, have your month number correspond to an index of an array containing the abbreviations (this is pretty basic, but ask if you don't understand) – David John Coleman II Sep 01 '17 at 04:37
-
3Please... How hard is it to just paste some of your data here? Do you really want to make it difficult for people to answer your question? – cs95 Sep 01 '17 at 04:37
1 Answers
1
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

jezrael
- 822,522
- 95
- 1,334
- 1,252
-
Are you sure? Downvotes means really bad answer. So why it was accepted? – jezrael Sep 01 '17 at 06:42
-