如何统计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
相关产品推荐
相关产品推荐

