【问题标题】:Pandas groupby aggregate passing group name to aggregatePandas groupby 聚合传递组名来聚合
【发布时间】:2018-10-17 18:03:18
【问题描述】:

在常见的使用模式中,我需要使用自定义聚合函数来聚合 DataFrame。 在这种特殊情况下,聚合函数需要知道当前组 为了正确执行聚合。

为每个组调用传递给DataFrameGroupBy.aggregate() 的函数,并为每列接收包含当前组和列中元素的系列。 我发现从聚合函数内部获取组名的唯一方法是将分组列添加到索引中,然后使用 x.index.get_level_values('power')[0]。举个例子:

def _tail_mean_user_th(x):
    power = x.index.get_level_values('power')[0]
    th = th_dict[power]  # this values changes with the group
    return x.loc[x > th].mean() - th

mbsize_df = (bursts_sel.set_index('power', append=True).groupby('power')
             .agg({'nt': _tail_mean_user_th}))

在我看来,聚合函数需要知道当前组是很常见的情况。在这种情况下是否有更直接的模式?


编辑:我在下面接受的解决方案包括在 GroupBy 对象上使用 apply 而不是 agg。两者的区别在于agg 分别为每个组和每列调用该函数,而apply 为每个组(一次所有列)调用该函数。一个微妙的结果是agg 将为当前组和列传递一个Series,其name 属性等于原始列名。相反,apply 将传递一个Series,其name 属性等于当前组(这是我的问题)。有趣的是,在对多列进行操作时,apply 将传递一个带有 name 属性(通常不存在于 DataFrames)的 DataFrame 设置为组名。因此,这种模式在一次聚合多个列时也适用。

更多信息见What is the difference between pandas agg and apply function?

【问题讨论】:

  • 如果将as_index=False 添加到groupbypower 列是否可以直接作为x 的属性使用?
  • @scnerd,as_index控制聚合后返回的dataframe的索引,而不是通过.agg调用的函数看到的索引。在这种情况下我想要as_index=True

标签: python pandas pandas-groupby


【解决方案1】:

如果您使用groupby + apply,则可以通过.name 属性获得:

df = pd.DataFrame({'a': [1, 2, 1, 2], 'b': [1, 1, 2, 2]})
def foo(g):
    print('at group %s' % g.name)
    return int(g.name) + g.sum()    

>>> df.b.groupby(df.a).apply(foo)
at group 1
at group 2
a
1    4
2    5
Name: b, dtype: int64

【讨论】:

  • 太好了,谢谢!我的感觉“一定有更好的方法”是对的。
猜你喜欢
  • 1970-01-01
  • 2014-11-23
  • 2022-01-21
  • 2019-08-10
  • 2017-11-03
  • 2021-09-19
  • 1970-01-01
  • 2018-09-29
  • 2020-01-28
相关资源
最近更新 更多