Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I convert "YYYY/MM" type date into "MMM-YYYY" in pandas in python

Tags:

python

pandas

What I want to do:

# I have col names in pandas DF such as :
data   2017/01   2017/02  2017/03 ....
 ABC     12       22        08    ....
 EFG     07       16        12    ....   

I want to convert col names:

data   Jan-2017   Feb-2017   Mar-2017  ....
 ABC     12       22        08         ....
 EFG     07       16        12         ....   

I have tried the following:

pd.to_datetime(pd.Series(['2017/01']), format="%Y/%m")

Which, resulted in:

  0   2017-01-01
  dtype: datetime64[ns]

But I am not sure how to get the result I want. Any idea?

like image 873
Madhu Sareen Avatar asked Jun 14 '17 06:06

Madhu Sareen


2 Answers

You are close, need DatetimeIndex.strftime:

df.columns = pd.to_datetime(df.columns, format="%Y/%m").strftime('%b-%Y')
print (df)
      Jan-2017  Feb-2017  Mar-2017
data                              
ABC         12        22         8
EFG          7        16        12

EDIT:

Thank you piRSquared for idea:

df.columns = pd.PeriodIndex(df.columns, freq='M').strftime('%b-%Y')
print (df)
      Jan-2017  Feb-2017  Mar-2017
data                              
ABC         12        22         8
EFG          7        16        12
like image 155
jezrael Avatar answered Oct 17 '22 01:10

jezrael


Use the arrow library. Arrow is supposed to be datetime for humans. It's clean, simple and intuitive.

import arrow
arrow.get('2017/03').format('MMM-YYYY')

returns Mar-2017

like image 1
Akshay Apte Avatar answered Oct 17 '22 01:10

Akshay Apte