【问题标题】:Pandas: Apply custom function to groups and store result in new columns in each groupPandas:将自定义函数应用于组并将结果存储在每个组的新列中
【发布时间】:2021-04-06 20:12:12
【问题描述】:

我正在尝试将自定义函数应用于 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    |               |              |
   -----------------------------------------------------------------

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

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    我认为你需要:

    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)
    

    【讨论】:

    • 我收到了这个错误:TypeError: 'function' object is not iterable
    • @Animeartist - 嗯,原因是输出是具有与原始df 相同索引的DataFrame,似乎在您的解决方案中将Column2 转换为索引。所以可能需要df = df.filter(lambda x: is_unique(x['Column1'])).groupby(['Column2']).apply(func).set_index('Column2')
    • 感谢您回复我,但不幸的是,我仍然遇到同样的错误。
    • df = df.filter(lambda x: is_unique(x['Column1'])).groupby(['Column2']).apply(func).set_index('Column2')。此行正在返回错误。
    • @Animeartist - 很难知道什么是错误,因为无法运行您的示例数据。那么您可以发布is_unique 进行可能的测试吗?
    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多