Pandas DataFrame 将单列除以列组的总和 [英] Pandas DataFrame divide single column by the sum of the column groups

查看:77
本文介绍了Pandas DataFrame 将单列除以列组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个 DataFrame,我想在其中找到每个元素对一个组的贡献的百分比.

I am working with a DataFrame where I want to find the % that each element contributes to a group.

例如,我有以下数据框

    a
Out[295]: 
  c1  c2  c3
0  a  p1   1
1  b  p1   2
2  c  p2   3
3  d  p3   4

我想用 c2 得到每个组的总和,然后将 c3 除以这个总和.我可以使用 groupby 函数来获取总和:

I want to get the sum of each group by c2 and then divide c3 by this sum. I can use the groupby function to get the sums:

b = a.groupby('c2').aggregate({'c3':sum})

b
Out[298]: 
    c3 
c2    
p1   3
p2   3
p3   4

但是,我不知道如何将 c3 列除以这些结果以获得以下结果:

But, then I don't know how to divide JUST the column c3 by those results to get the following:

  c1  c2  c3
0  a  p1   0.333
1  b  p1   0.667
2  c  p2   1.000
3  d  p3   1.000

推荐答案

你可以使用 transform

b = a.groupby('c2').c3.transform('sum')
b
Out[451]: 
0    3
1    3
2    3
3    4
Name: c3, dtype: int64
a['c3']/=b
a
Out[453]: 
  c1  c2        c3
0  a  p1  0.333333
1  b  p1  0.666667
2  c  p2  1.000000
3  d  p3  1.000000

这篇关于Pandas DataFrame 将单列除以列组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆