在python中查找分类变量的比率

2024-07-02 10:17:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧df,在其中我有客户ID,他们的purcase要么打折要么正常价格。我想找出他们购买的顾客比率。你知道吗

Customer Price_Type
 1        Discount
 1        Discount
 1        Discount
 1        DealerNet        
 1        DealerNet 
 1        DealerNet 
 2        DealerNet 
 2        DealerNet 
 2        DealerNet
 2        DealerNet

预期输出为:

Customer  at_Dicount at_DealerNet
  1          50              50
  2           0              100

我尝试了groupby函数,但没有得到我想要的。你知道吗


Tags: 数据iddf客户type价格discountcustomer
1条回答
网友
1楼 · 发布于 2024-07-02 10:17:44

^{}normalize一起使用,乘以100并将数据清理-^{}^{}一起使用:

df1 = (pd.crosstab(df['Customer'], df['Price_Type'], normalize='index')
         .mul(100)
         .reset_index()
         .rename_axis(None, axis=1))
print (df1)
   Customer  DealerNet  Discount
0         1       50.0      50.0
1         2      100.0       0.0

相关问题 更多 >