Python Pandas计算按产品数排序的前四品牌各品类平均价格
Pandas 实现代码
以下是完整可运行的实现代码,每步均添加了注释,你可以根据自己的实际数据源调整:
import pandas as pd # ---------------------- 1. 构造示例数据,如果你已有对应df可删除此部分 ---------------------- data = { "brand": ["Apple", "Huawei", "Apple", "Samsung", "Apple", "xiomi", "Huawei"], "price": [499.0, 200.0, 150.0, 800.0, 55.0, 25.0, 140.0], "category": ["phone", "phone", "headphones", "phone", "accesory", "accesory", "headphones"] } df = pd.DataFrame(data) # ---------------------- 2. 筛选总产品数前4的品牌 ---------------------- # 统计各品牌总产品数,降序排序后取前4个品牌 top4_brand_list = df["brand"].value_counts(ascending=False).head(4).index.tolist() # 过滤仅保留前4品牌的所有数据 filter_df = df[df["brand"].isin(top4_brand_list)] # ---------------------- 3. 计算各品牌对应品类的平均价格 ---------------------- # 生成透视表,指定行索引为品牌、列索引为品类、值为平均价格,按要求调整列顺序后保留两位小数 result_df = pd.pivot_table( filter_df, index="brand", columns="category", values="price", aggfunc="mean" ).reindex(columns=["phone", "headphones", "accesory"]).round(2) # 如果品牌无对应品类时需要填充空值为0,可以取消注释下行代码 # result_df = result_df.fillna(0) # 输出结果 print(result_df)
运行输出示例
category phone headphones accesory brand Apple 499.0 150.0 55.0 Huawei 200.0 140.0 NaN Samsung 800.0 NaN NaN xiomi NaN NaN 25.0
内容的提问来源于stack exchange,提问作者Regnas01
相关产品推荐
相关产品推荐

