现在我在一个pandas数据框架中有一个这样的专栏:
Year_Quarter
2014Q1
2015Q1
2015Q2
2016Q3
我通过使用以下代码转换另一列日期得到了这一列:
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)
如何将此日期格式转换为:
Q12014
Q12015
Q22015
Q32016
谢谢你的帮助!
您可以尝试使用strftime
来获取自定义格式:
combine['Year_Quarter'] = pd.to_datetime(combine['Publish Date']).dt.to_period("Q").dt.strftime('Q%q%Y')
或者,正如@Barmar和@Anky在评论中所建议的,您也可以将该列切分:
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])
两个输出:
combine['Year_Quarter']
Q12014
Q12015
Q22015
Q32016