How do I convert a date like "YYYY / MM" to "MMM-YYYY" in pandas in python

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 tried the following:

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

Which led to:

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

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

+4
source share
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:

Thanks to piRSquared for the 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
+5
source

Use the arrow library. The arrow is supposed to be a date for people. It is clean, simple and intuitive.

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

returns Mar-2017

+1
source

Source: https://habr.com/ru/post/1679207/


All Articles