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

Pandas按日分组取最大值后如何将日期与最大值拆分为独立两列

调整代码方案

原有代码返回结果不符合预期是两个原因导致:groupby默认将分组键设为行索引不会放到列中,且agg传入带列表的聚合规则会生成多级列索引。

方案1:最小改动适配原有写法

df_new = df.groupby(pd.Grouper(key="longtime",freq="D")).agg({df.columns[1]: np.max})
# 把索引的longtime转为普通列
df_new = df_new.reset_index()
# 重命名列符合需求
df_new.columns = ["longtime", "amax"]
print(df_new)

方案2:推荐的命名聚合写法,结构更清晰

# as_index=False 直接将分组键作为列返回,不用额外处理索引
df_new = df.groupby(pd.Grouper(key="longtime", freq="D"), as_index=False).agg(
    amax=(df.columns[1], np.max) # 直接指定输出列名、对应聚合列和聚合函数
)
print(df_new)

内容的提问来源于stack exchange,提问作者mika

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:15:03