python,pandas,求前四大品牌的平均价格,dataframe

python, pandas, find average prices of the top four brands, dataframe

您好,我需要获取前四大品牌的平均价格,根据类别的总和找到前四大品牌,只有三个类别。前四不是谁的钱多,谁的产品组合多。

这是数据框:

brand     price   category
Apple     499.0    phone
Huawei    200.0    phone
Apple     150.0    headphones
Samsung   800.0    phone
Apple     55.0     accesory
xiomi     25.0     accesory
Huawei    140.0    headphones

这是我要的结果,以品牌为指标,四个品牌的平均价格,价格保留2位小数

         phone    headphones   accesory
brand_1  XXXX         XXXX        XXXX
brand_2  XXXX         XXXX        XXXX
brand_3  XXXX         XXXX        XXXX
brand_4  XXXX         XXXX        XXXX

我是初学者,没有太多经验,希望大家能帮帮我,谢谢

尝试:

# get top 4 brands by size:
top_4 = df.groupby("brand").size().nlargest(4)

# pivot the table, format it and get top_4 brands:
df_out = (
    df.pivot_table(
        index="brand",
        columns="category",
        values="price",
        aggfunc="mean",
        fill_value=0,
    )
    .apply(lambda x: ["{:.2f}".format(v) for v in x])
    .loc[top_4.index]
)
print(df_out)

打印:

category accesory headphones   phone
brand                               
Apple       55.00     150.00  499.00
Huawei       0.00     140.00  200.00
Samsung      0.00       0.00  800.00
xiomi       25.00       0.00    0.00