【问题标题】:Pandas: How to return multiple columns with a custom apply function on a groupby objectPandas:如何在 groupby 对象上使用自定义应用函数返回多列
【发布时间】:2021-10-01 17:11:03
【问题描述】:

基本思想是我的计算涉及数据框中的多个列并返回多个列,我想将它们集成到数据框中。 我想做这样的事情:

df = pd.DataFrame({'id':['i1', 'i1', 'i2', 'i2'], 'a':[1,2,3,4], 'b':[5,6,7,8]})

def custom_f(a, b):
    computation = a+b
    return computation + 1, computation*2

df['c1'], df['c2'] = df.groupby('id').apply(lambda x: custom_f(x.a, x.b))

期望的输出:

    id  a   b  c1     c2
0   i1  1   5  7      12
1   i1  2   6  9      16
2   i2  3   7  11     20
3   i2  4   8  13     24

我知道如何一次处理一列,但实际上使用两列的“计算”操作非常昂贵,所以我试图弄清楚如何只能运行一次。

编辑:我意识到给定的示例可以在没有 groupby 的情况下解决,但是对于实际“计算”的用例,我正在使用 groupby,因为我使用每个组中数组的第一个和最后一个值用于我的计算。为了简单起见,我省略了它,但想象一下它是必需的。

【问题讨论】:

  • 嗨!以下任何一个答案是否有效?如果是这样并且如果您愿意,您可以考虑accepting 其中之一向其他人发出问题已解决的信号。如果没有,您可以提供反馈,以便改进(或完全删除)

标签: python pandas pandas-groupby apply


【解决方案1】:
df['c1'], df['c2'] = custom_f(df['a'], df['b']) # you dont need apply for your desired output here

【讨论】:

  • 谢谢,我认为我的示例可能过于简单。在我的实际用例中,我使用 groupby,因为我需要知道每个分组数据帧数组的起点/终点以进行计算。
【解决方案2】:

你可以试试:

def custom_f(a, b):
    computation = a+b
    return pd.concat([(computation + 1),(computation*2)],axis=1)

最后:

df[['c1','c2']]=df.groupby('id').apply(lambda x: custom_f(x.a, x.b)).values

df的输出:

    id  a   b   c1  c2
0   i1  1   5   7   12
1   i1  2   6   9   16
2   i2  3   7   11  20
3   i2  4   8   13  24

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 2023-01-23
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    相关资源
    最近更新 更多