首页 > 解决方案 > Pandas:将自定义函数应用于组并将结果存储在每个组的新列中

问题描述

我正在尝试将自定义函数应用于 groupby 对象中的每个组,并将结果存储到每个组本身的新列中。该函数返回 2 个值,我想将这些值分别存储到每组的 2 列中。

我试过这个:

# Returns True if all values in Column1 is different.
def is_unique(x):
    status = True
    if len(x) > 1:
        a = x.to_numpy() 
        if (a[0] == a).all():
            status = False
    return status

# Finds difference of the column values and returns the value with a message.
def func(x):
    d  = (x['Column3'].diff()).dropna()).iloc[0]
    return d, "Calculated!"

# is_unique() is another custom function used to filter unique groups.
df[['Difference', 'Message']] = df.filter(lambda x: is_unique(x['Column1'])).groupby(['Column2']).apply(lambda s: func(s))

但我收到错误:'DataFrameGroupBy' object does not support item assignment

我不想重置索引并想使用该get_group函数查看结果。最终的数据框应如下所示:

df.get_group('XYZ')


   -----------------------------------------------------------------
   |   Column1 | Column2 | Column3  |  Difference   |    Message   |
   -----------------------------------------------------------------
   | 0   A     |   XYZ   |   100    |               |              |
   ----------------------------------               |              |
   | 1   B     |   XYZ   |    20    |      70       |  Calculated! |
   ----------------------------------               |              |
   | 2   C     |   XYZ   |    10    |               |              |
   -----------------------------------------------------------------

实现此结果的最有效方法是什么?

标签: pythonpandasdataframepandas-groupby

解决方案


我认为你需要:

def func(x):
    d  = (x['Column3'].diff()).dropna()).iloc[0]
    last = x.index[-1]
    x.loc[last, 'Difference'] = d
    x.loc[last, 'Message'] = "Calculated!"
    return x

df1 = df.filter(lambda x: is_unique(x['Column1']))

df1 = df1.groupby(['Column2']).apply(func)

推荐阅读