Now I have a column like this in a pandas dataframe:
Year_Quarter
2014Q1
2015Q1
2015Q2
2016Q3
I got this column by converting another column of date using the following code:
combine['Publish Date'] = pd.to_datetime(combine['Publish Date']).dt.strftime('%Y-%m-%d')
combine['Year_Quarter'] = pd.to_datetime(combine['Publish Date']).dt.to_period('Q').astype(str)
How do I convert this date format into:
Q12014
Q12015
Q22015
Q32016
Thanks for your help!
You could try this with strftime
to get the custom format:
combine['Year_Quarter'] = pd.to_datetime(combine['Publish Date']).dt.to_period("Q").dt.strftime('Q%q%Y')
Or as is suggested in the comments by @Barmar and @anky, you could slice the column too:
combine['Year_Quarter'] = pd.to_datetime(combine['Publish Date']).dt.to_period('Q').astype(str)
combine['Year_Quarter']=combine['Year_Quarter'].str[-2:].add(combine['Year_Quarter'].str[:4])
Both outputs:
combine['Year_Quarter']
Q12014
Q12015
Q22015
Q32016
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.