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

如何按分组提取DataFrame列最大值并创建新DataFrame

按Topic分组提取Num列最大值的解决方案

核心实现代码

你需要结合groupby()分组和max()求最大值,再通过reset_index()调整格式,代码如下:

import pandas as pd

# 构造原始DataFrame(如果你的df已存在可跳过这部分)
df = pd.DataFrame({
    'topic': ['a01', 'a01', 'a01', 'a02', 'a02', 'a02', 'a02', 'a03', 'a03'],
    'num': [1, 1, 2, 1, 3, 2, 3, 2, 1]
})

# 分组求最大值并生成目标DataFrame
newdf = df.groupby('topic')['num'].max().reset_index()

代码说明

  • groupby('topic'):将数据按topic列的值分组,每个topic对应一组数据
  • ['num'].max():对每组的num列计算最大值
  • reset_index():将分组后的topic索引转为普通列,同时生成从0开始的整数索引,匹配你需要的格式

运行结果

执行后newdf的内容如下:

topic  num
0    a01    2
1    a02    3
2    a03    2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:15:07