如何在pandas中找到groupby中总数的百分比 [英] how to find percentage of total in groupby in pandas

查看:75
本文介绍了如何在pandas中找到groupby中总数的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫中有以下数据框

I have following dataframe in pandas

  Date        tank     hose     quantity     count      set     flow
  01-01-2018  1        1        20           100        211     12.32
  01-01-2018  1        2        20           200        111     22.32
  01-01-2018  1        3        20           200        123     42.32
  02-01-2018  1        1        10           100        211     12.32
  02-01-2018  1        2        10           200        111     22.32
  02-01-2018  1        3        10           200        123     42.32

我想计算 quantitycountDatetank 分组的百分比.我想要的数据框

I want to calculate percentage of quantity and count grouping by Date and tank. My desired dataframe

  Date        tank   hose   quantity   count   set   flow    perc_quant  perc_count
  01-01-2018  1        1    20         100     211   12.32   33.33       20
  01-01-2018  1        2    20         200     111   22.32   33.33       40
  01-01-2018  1        3    20         200     123   42.32   33.33       40
  02-01-2018  1        1    10         100     211   12.32   25          20
  02-01-2018  1        2    20         200     111   22.32   50          40
  02-01-2018  1        3    10         200     123   42.32   25          40

我正在做以下事情来实现这一目标

I am doing following to achieve this

   test = df.groupby(['Date','tank']).apply(lambda x:
                                             100 * x / float(x.sum()))

推荐答案

使用 GroupBy.transform 带有 lambda 函数,add_prefixjoin 到原始:

Use GroupBy.transform with lambda function, add_prefix and join to original:

f = lambda x: 100 * x / float(x.sum())
df = df.join(df.groupby(['Date','tank'])['quantity','count'].transform(f).add_prefix('perc_'))

或者指定新的列名:

df[['perc_quantity','perc_count']] = (df.groupby(['Date','tank'])['quantity','count']
                                        .transform(f))

<小时>

print (df)
         Date  tank  hose  quantity  count  set   flow  perc_quantity  \
0  01-01-2018     1     1        20    100  211  12.32      33.333333   
1  01-01-2018     1     2        20    200  111  22.32      33.333333   
2  01-01-2018     1     3        20    200  123  42.32      33.333333   
3  02-01-2018     1     1        10    100  211  12.32      33.333333   
4  02-01-2018     1     2        10    200  111  22.32      33.333333   
5  02-01-2018     1     3        10    200  123  42.32      33.333333   

   perc_count  
0        20.0  
1        40.0  
2        40.0  
3        20.0  
4        40.0  
5        40.0  

这篇关于如何在pandas中找到groupby中总数的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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