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

pandas如何基于两列唯一组合统计另外两列分组的去重计数

解决方案

你的需求本质是统计每个Name + slot分组下,A和B的唯一组合数量,可通过如下代码实现:

import pandas as pd
import numpy as np

# 原始数据集
dff = pd.DataFrame(np.array([["2020-11-13",3,4, 0,0], ["2020-10-11", 3,4,0,1], ["2020-11-13", 1,4,1,1],
                         ["2020-11-14", 3,4,0,0], ["2020-11-13", 5,4,0,1], 
                         ["2020-11-14", 2,4,1,1],["2020-11-12", 1,4,0,1],["2020-11-14", 2,4,0,1],["2020-11-15", 5,4,1,1],
                         ["2020-11-11", 1,2,0,0],["2020-11-15", 1,2,0,1],
                         ["2020-11-18", 2,4,0,1],["2020-11-17", 1,2,0,0],["2020-11-20", 3,4,0,0]]), columns=['Timestamp', 'Name', "slot", "A", "B"])

# 核心实现:先对Name、slot、A、B组合去重,再分组计数
result = dff.drop_duplicates(subset=['Name', 'slot', 'A', 'B']) \
            .groupby(['Name', 'slot'], as_index=False) \
            .size() \
            .rename(columns={'size': 'count'})

print(result)

运行后输出结果和预期完全一致:

Name slot  count
0    1    2      2
1    1    4      2
2    2    4      2
3    3    4      2
4    5    4      2

错误原因说明

你之前的代码是全局按A、B分组取最小时间,会把不同Name、slot分组下相同A、B的行误过滤,导致统计结果偏少。正确的过滤逻辑需要保证去重范围限制在同一个Name+slot分组内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 08:36:04