【问题标题】:Custom aggregation that acts on more than one columns in pandas作用于 pandas 中多个列的自定义聚合
【发布时间】:2022-12-16 21:19:18
【问题描述】:

请注意,这个问题确实不是询问在 pandas 中我们是否可以在聚合期间对多个列应用函数。这是一个例子:

数据框:

A x y
foo 0 0
foo 1 1
foo 2 2
foo 3 3
bar 0 2
bar 2 3
bar 4 4
bar 6 5

我想按 A 列对这个表进行分组,并计算每组的线性回归 y=k*x+b。所以我们要实现这个:

A k b
foo 1.0 0.0
bar 0.5 2.0

我尝试按索引 A 分组,并使用 aggregate 方法:

grouped = table.groupby('A')
grouped.aggregate(f)

def f():
    pass

虽然我发现此方法会将表格拆分为系列并将该系列提供给函数f,因此f 无法同时访问两列。

那么,我该如何做这种以拆分-应用-组合的方式作用于多列的“聚合”功能呢?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果需要同时处理多列使用GroupBy.apply

    def f(x):
        print (x)
    
    grouped = table.groupby('A').apply(f)
    

    【讨论】:

      【解决方案2】:

      采用:

      from scipy.stats import linregress
      
      df.groupby('A').apply(lambda g: pd.Series(linregress(g['x'], g['y'])[:2], index=['k', 'b']))
      

      【讨论】:

        猜你喜欢
        • 2019-06-08
        • 1970-01-01
        • 1970-01-01
        • 2021-04-26
        • 2019-11-05
        • 1970-01-01
        • 2018-03-30
        • 2017-08-04
        • 2016-10-10
        相关资源
        最近更新 更多