如何为 Python 中的每个分组应用用户定义的函数

Mr.*_*ata 5 python user-defined-functions pandas pandas-groupby

我有一个数据框 df1 如下:

Country|Month|Revenue
-------|-----|-------
US     |Jan  |100
US     |Feb  |200
US     |Mar  |300
Canada |Jan  |200
Canada |Feb  |400
Canada |Mar  |500
Run Code Online (Sandbox Code Playgroud)

我想应用用户定义函数,如下所示:

df3=df1.groupby(['Country'])['Revenue'].my_cool_func()
def my_cool_func():
    b = max(Revenue)-Min(Revenue)
    c=b/2
    return c
Run Code Online (Sandbox Code Playgroud)

我的 df3 最终输出应该是:

Country|my_cool_func_rev
-------|----------------
US     |100
Canada |150
Run Code Online (Sandbox Code Playgroud)

如何使用用户定义函数来获得上述输出?

jez*_*ael 3

GroupBy.apply您可以在与 一起使用的函数中使用and Series,因此也可以使用Series.maxand Series.min:

def my_cool_func(x):
    #print (x)
    return (x.max() - x.min()) / 2

df3=df1.groupby(['Country'])['Revenue'].apply(my_cool_func).reset_index()
print (df3)
  Country  Revenue
0  Canada    150.0
1      US    100.0
Run Code Online (Sandbox Code Playgroud)

或者:

df3=df1.groupby(['Country'])['Revenue'].apply(lambda x:(x.max() - x.min()) / 2).reset_index()
print (df3)
  Country  Revenue
0  Canada    150.0
1      US    100.0
Run Code Online (Sandbox Code Playgroud)

编辑:使用Series.std:

def my_cool_func(x):
    b = x.std()
    c=b/2
    return c

df3=df1.groupby(['Country'])['Revenue'].apply(my_cool_func).reset_index()
print (df3)
  Country    Revenue
0  Canada  76.376262
1      US  50.000000
Run Code Online (Sandbox Code Playgroud)