如何统计DataFrame中各供应商的独有产品数量?
统计各供应商独有产品数量
原始数据
vendor product a grape a peach a orange b peach b strawberry b apple c grape c peach c pineapple
需求
统计每个供应商拥有的、其他供应商都没有的产品数量,期望输出:
vendor num_exclusive_products a 1 b 2 c 1
简洁实现方案
用Pandas可以轻松搞定,这里提供两种流畅的写法:
方法一:分步清晰版
先定位出仅被单个供应商持有的产品,再按供应商统计这类产品的数量:
import pandas as pd # 构造示例DataFrame df = pd.DataFrame({ 'vendor': ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], 'product': ['grape', 'peach', 'orange', 'peach', 'strawberry', 'apple', 'grape', 'peach', 'pineapple'] }) # 1. 筛选出仅属于一个供应商的产品 single_vendor_products = df.groupby('product')['vendor'].nunique() == 1 target_products = single_vendor_products[single_vendor_products].index # 2. 统计各供应商的独有产品数量 result = df[df['product'].isin(target_products)] \ .groupby('vendor') \ .size() \ .reset_index(name='num_exclusive_products') print(result)
方法二:链式调用精简版
用transform给每行数据标记对应产品的供应商总数,直接筛选后分组计数,代码更紧凑:
result = df.assign( vendor_count=df.groupby('product')['vendor'].transform('nunique') ).query('vendor_count == 1') \ .groupby('vendor') \ .size() \ .reset_index(name='num_exclusive_products')
两种方法运行后都能得到你想要的输出结果,逻辑直观易读。
内容的提问来源于stack exchange,提问作者teogj
相关产品推荐
相关产品推荐

