如何使用Python将pandas数据集datetime转换为季度并按location分组
你当前的代码已经完成了日期转季度的核心逻辑,只需要调整两处即可达到预期效果:
- 格式化季度字符串时把原代码里的
.替换为空格,匹配你需要的Q1 22格式 - 格式转换完成后按
location字段分组去重即可(同个location下的季度值统一,取第一个、最小值等规则均可)
完整可运行代码如下:
# 转换列为日期格式 df['start'] = pd.to_datetime(df['start']) df['end'] = pd.to_datetime(df['end']) # 转换为指定格式的季度字符串 df['start'] = pd.PeriodIndex(df['start'], freq='Q').strftime('Q%q %y') df['end'] = pd.PeriodIndex(df['end'], freq='Q').strftime('Q%q %y') # 按location分组去重,得到最终结果 result_df = df.groupby('location', as_index=False).first()
如果你的实际业务中存在同个location跨多个季度的情况,需要取该位置的最早开始季度和最晚结束季度,可以把分组逻辑调整为:
result_df = df.groupby('location', as_index=False).agg( start=('start', 'min'), end=('end', 'max') )
内容的提问来源于stack exchange,提问作者Lynn
相关产品推荐
相关产品推荐

