python - python - 如何在python中将日期时间格式Year-Quarter转换为Quarter-Year?
问题描述
现在我在 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
推荐阅读
- excel - Excel 图表导出为空白
- android - 与 FileProvider 共享日志文件失败
- javascript - 这是在旧版本节点中避免回调地狱的可接受方法吗?
- jenkins - 使用 Jenkins CI/CD 管道在 EC2 中的 SVN 结帐项目的物理位置
- matlab - 误码率计算 15,11 汉明码图
- ios - 使用 UIAppearence 设置 UITableViewCell 选择的背景颜色不起作用
- html - HTML输出文本不会根据闪亮的CSS文件而改变
- powershell - 从 nuget 帮助输出中选择文本时,PowerShell 退出代码 1
- oracle - ORA-14287在新表空间上重建复合分区索引
- nginx - 设置过期标头 nginx conf 仅适用于前端