Pandas 提供了 apply
方法来按照自定义函数对分组进行应用。下面是一个示例代码:
import pandas as pd
# 创建示例数据
data = {'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'two', 'two', 'one', 'two', 'one'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]}
df = pd.DataFrame(data)
# 自定义函数
def custom_func(x):
return x['C'].sum() + x['D'].sum()
# 按照 'A' 列进行分组,并应用自定义函数
result = df.groupby('A').apply(custom_func)
print(result)
输出结果为:
A
bar 170
foo 146
dtype: int64
在上面的示例中,首先创建了一个带有四列的 DataFrame。然后定义了一个自定义函数 custom_func
,用来计算分组中 'C' 列和 'D' 列的总和。最后使用 groupby
方法按照 'A' 列进行分组,并使用 apply
方法应用自定义函数。结果返回了按照 'A' 列分组后,每个分组调用自定义函数后的结果。