如何在Pandas DataFrame中统计各产品不同星级的出现次数
问题:统计每个产品各星级的出现次数(含未出现星级的0值)
原始Pandas DataFrame结构如下:
product stars 10717 4 10717 5 10717 5 10717 5 10717 3 10717 2 10717 2 10711 2 10711 1 10711 5 10711 1 10711 1 10711 5 10711 2
该DataFrame包含数千行数据,需要统计每个不同product的1-5星各自出现次数,未出现的星级需显示次数为0。
尝试过的方法:
dp = df.product.unique() for key in dp: df[(df['product'] == key)].value_counts()
得到的结果:
product stars 10717 5 3 4 1 3 1 2 2 dtype: int64 product stars 10711 5 2 2 3 1 2 dtype: int64
期望得到的DataFrame格式:
product stars number_stars 10717 5 3 10717 4 1 10717 3 1 10717 2 2 10717 1 0 10711 5 2 10711 4 0 10711 3 0 10711 2 3 10711 1 2
解决方案
可以通过分组统计+重新索引补全的方式高效实现,无需遍历,适合大数据量:
import pandas as pd # 1. 分组统计每个产品各星级的出现次数 star_counts = df.groupby(['product', 'stars']).size().rename('number_stars') # 2. 生成所有产品与1-5星的完整组合索引 all_products = df['product'].unique() all_stars = range(1, 6) # 覆盖1到5星 full_index = pd.MultiIndex.from_product( [all_products, all_stars], names=['product', 'stars'] ) # 3. 重新索引补全缺失项,并用0填充 result_df = star_counts.reindex(full_index, fill_value=0).reset_index() # 查看结果 print(result_df)
代码解释:
groupby(['product', 'stars']).size():按产品和星级分组,统计每组的行数(即出现次数),并重命名列名为number_stars。MultiIndex.from_product:生成所有产品与1-5星的笛卡尔积,确保每个产品都有1-5星的完整条目。reindex(full_index, fill_value=0):将统计结果对齐到完整索引,缺失的条目(未出现的星级)填充为0。reset_index():将多级索引转换为普通列,得到目标格式的DataFrame。
运行后即可得到符合期望的结果,且处理数千行数据的效率远高于遍历方法。
内容的提问来源于stack exchange,提问作者codyLine
相关产品推荐
相关产品推荐

