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

在Pandas中展示并分组DataFrame重复行的实现需求

按重复行分组聚合DataFrame数据

原始DataFrame:

CC BF FA WC Strength
1  2  3  4   1
2  3  4  5   6
1  2  3  4   8
1  2  3  4   4
2  3  4  5   7

需求说明:

移除Strength列后,行1、3、4为一组重复行,行2、5为另一组重复行。需要将这些重复行分组后,聚合得到每组的Strength最小值、最大值,以及该组的行数。

期望输出的DataFrame:

CC BF FA WC Strength_min Strength_max Count
1  2  3  4  1            8             3
2  3  4  5  6            7             2

实现代码(Pandas):

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'CC': [1, 2, 1, 1, 2],
    'BF': [2, 3, 2, 2, 3],
    'FA': [3, 4, 3, 3, 4],
    'WC': [4, 5, 4, 4, 5],
    'Strength': [1, 6, 8, 4, 7]
})

# 分组聚合
result_df = df.groupby(['CC', 'BF', 'FA', 'WC'], as_index=False).agg(
    Strength_min=('Strength', 'min'),
    Strength_max=('Strength', 'max'),
    Count=('Strength', 'count')
)

print(result_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:42:36