【发布时间】:2019-04-12 04:24:08
【问题描述】:
假设我有一个包含 3 列的数据框。我想按其中一列对其进行分组,并使用自定义聚合函数为每个组计算一个新值。
这个新值具有完全不同的含义,并且它的列不存在于原始数据框中。因此,实际上,我想在groupby() + agg() 转换期间更改数据框的形状。原始数据框看起来像 (foo, bar, baz) 并且有一个范围索引,而生成的数据框只需要有 (qux) 列和 baz 作为索引。
import pandas as pd
df = pd.DataFrame({'foo': [1, 2, 3], 'bar': ['a', 'b', 'c'], 'baz': [0, 0, 1]})
df.head()
# foo bar baz
# 0 1 a 0
# 1 2 b 0
# 2 3 c 1
def calc_qux(gdf, **kw):
qux = ','.join(map(str, gdf['foo'])) + ''.join(gdf['bar'])
return (None, None) # but I want (None, None, qux)
df = df.groupby('baz').agg(calc_qux, axis=1) # ['qux'] but then it fails, since 'qux' is not presented in the frame.
df.head()
# qux
# baz
# 0 1,2ab
# 1 3c
如果我尝试从聚合函数返回与原始数据帧中的列数不同的值,则上面的代码会产生错误 ValueError: Shape of passed values is (2, 3), indices imply (2, 2)。
【问题讨论】:
-
你想要的输出到底是什么?
-
没有预期的输出,我不确定我是否理解。但是您可能想要
apply而不是聚合,并且可能想要返回pd.Series而不是tuple -
@rahlf23 刚刚添加了一个示例,请查看更新后的问题。
-
@RafaelC
apply + series单值可能有效,但我仍然需要一个组。我可以在应用某些东西时进行分组吗?
标签: python pandas dataframe pandas-groupby