【问题标题】:lambda custom aggregate functionlambda 自定义聚合函数
【发布时间】:2015-07-08 01:01:32
【问题描述】:

我正在使用如下所示的数据集(值已更改,实际数据要大得多)

fruit_type, temp, count
apple, 12, 4
apple, 14, 6
pear, 12, 6
pear, 16, 2
grape 12, 5
peach, 9, 33
peach 6, 3

我正在尝试利用一个 numpy agg 函数来查找每个计数在每个温度下的总计数百分比。我还想要一个代表总数的列。下面是我一直在尝试的代码。

data3 = data2.groupby('fruit_type')['count'].agg({
    'prob' : lambda count: ((count) / count.sum()),
    'total' : lambda count: count.size
    })

温度值是离散的。我希望 count 逐行汇总,其中总计数总和按水果类型分组。请让我知道我的代码有什么问题。

【问题讨论】:

    标签: python numpy pandas lambda


    【解决方案1】:

    问题是第一个lambda count: count/count.sum()。它返回与组相同的形状,而不是将其聚合为标量。

    您可能想要使用transform 而不是agg

    import pandas as pd
    import numpy as np
    
    # suppose this is your df
    df
    
    Out[83]: 
      fruit_type   temp   count
    0      apple     12       4
    1      apple     14       6
    2       pear     12       6
    3       pear     16       2
    4      grape     12       5
    5      peach      9      33
    6      peach      6       3
    
    
    # prob part
    df['prob'] = df.groupby('fruit_type')['count'].transform(lambda count: ((count) / count.sum()))
    
    # total part
    df['total_count'] = df.groupby('fruit_type')['count'].transform(lambda count: count.sum())
    
    df
    
    Out[87]: 
      fruit_type  temp  count    prob  total_count
    0      apple    12      4  0.4000           10
    1      apple    14      6  0.6000           10
    2       pear    12      6  0.7500            8
    3       pear    16      2  0.2500            8
    4      grape    12      5  1.0000            5
    5      peach     9     33  0.9167           36
    6      peach     6      3  0.0833           36
    

    【讨论】:

    • 我怎样才能让它聚合更大的标量?
    • @user3609179 我添加了一些代码来说明如何使用transform。另外,是否有一个特殊的原因,为什么你想要 'total' : lambda count: count.size 中的 size 而不是 .sum()
    • 我想要按水果计算的总和。这在您发布的当前 sn-p 中有效吗?
    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 2016-01-30
    • 2012-01-19
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    相关资源
    最近更新 更多