【问题标题】:calculate the percentage contribution of a value in a column in python计算python中列中值的百分比贡献
【发布时间】:2018-06-20 20:43:00
【问题描述】:

我有以下数据框

 item1  item2    item3    
  x      y         z    
  x1     y1        z1   
  x      y2        z2   
  x      y         z1
  x2     y         z         
  x2     y1        z2     

我想找出列中每个值对列中所有值的百分比贡献(item1 中 x,x1,x2 的贡献与 item2 和 item3 相同)

以下必须是结果数据框。

item1  %con_item1  item2  %con_item2  item3 %con_item3
x          50       y        50         z       33.33
x1         16.66    y1       33.33      z1      33.33
x2         33.33    y2       16.66      z2      33.33      

【问题讨论】:

  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这种努力的一个好方法是添加Minimal, complete, verifiable example。在发帖前检查您应该完成的intro tour,尤其是How to Ask

标签: python pandas


【解决方案1】:

使用value_counts 并将normalize 参数设置为True:

pd.concat([df[i].value_counts(normalize=True).reset_index() for i in df.columns], axis=1)

输出:

  index     item1 index     item2 index     item3
0     x  0.500000     y  0.500000    z1  0.333333
1    x2  0.333333    y1  0.333333    z2  0.333333
2    x1  0.166667    y2  0.166667     z  0.333333

使用缩放和列命名更新答案:

pd.concat([df[i].value_counts(normalize=True)
                .mul(100.0)
                .rename_axis(i)
                .reset_index(name='%con_'+i)  for i in df.columns], axis=1)

输出:

  item1  %con_item1 item2  %con_item2 item3  %con_item3
0     x   50.000000     y   50.000000    z1   33.333333
1    x2   33.333333    y1   33.333333    z2   33.333333
2    x1   16.666667    y2   16.666667     z   33.333333

【讨论】:

  • @user3483203 谢谢。寻找一种简洁的方式来命名 OP 想要的列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 2020-09-15
  • 2022-01-01
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 2021-10-17
相关资源
最近更新 更多