You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将pandas数据集datetime转换为季度并按location分组

你当前的代码已经完成了日期转季度的核心逻辑,只需要调整两处即可达到预期效果:

  1. 格式化季度字符串时把原代码里的.替换为空格,匹配你需要的Q1 22格式
  2. 格式转换完成后按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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:36:09