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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With