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

如何统计DataFrame中满足BR/NBR条件的唯一ID数量?

解决方案

针对你的需求,我们可以通过Pandas的分组聚合功能高效计算四类指标,以下是完整实现:

实现代码

import pandas as pd

# 示例数据
data = {
    'id': [1, 1, 2, 2, 3, 3, 4, 5, 5, 6],
    'change': ['BR', 'NBR', 'BR', 'NBR', 'BR', 'BR', 'BR', 'NBR', 'NBR', 'BR']
}
df = pd.DataFrame(data)

# 按id分组,计算每个id的关键特征
id_summary = df.groupby('id')['change'].agg(
    has_at_least_one_br=lambda x: (x == 'BR').any(),
    has_at_least_one_nbr=lambda x: (x == 'NBR').any(),
    all_br=lambda x: (x == 'BR').all(),
    all_nbr=lambda x: (x == 'NBR').all()
).reset_index()

# 统计各类id的数量
count_br_at_least_one = id_summary['has_at_least_one_br'].sum()
count_nbr_at_least_one = id_summary['has_at_least_one_nbr'].sum()
count_all_br = id_summary['all_br'].sum()
count_all_nbr = id_summary['all_nbr'].sum()

# 输出结果
print(f"cases of ids with atleast one instance where change = 'BR' = {count_br_at_least_one}")
print(f"cases of ids with atleast one instance where change = 'NBR' = {count_nbr_at_least_one}")
print(f"cases of ids where all changes = 'BR' = {count_all_br}")
print(f"cases of ids where all changes = 'NBR'= {count_all_nbr}")

输出结果

运行代码后将得到与预期一致的结果:

cases of ids with atleast one instance where change = 'BR' = 5
cases of ids with atleast one instance where change = 'NBR' = 3
cases of ids where all changes = 'BR' = 3
cases of ids where all changes = 'NBR'= 1

代码说明

  • groupby('id')['change']:按唯一标识id分组,仅对change列进行聚合计算
  • (x == 'BR').any():判断当前id的记录中是否存在至少一条BR
  • (x == 'BR').all():判断当前id的所有记录是否均为BR
  • 对布尔类型的特征列求和时,True会被自动转换为1,False转换为0,直接得到符合条件的id数量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:17:34