如何在Pandas中对多个列进行分组后,对每个组应用自定义的聚合函数?请举例说明。

# 在Pandas中,可以通过`groupby`方法对多个列进行分组,然后使用`apply`或`agg`方法对每个组应用自定义的聚合函数。
# 以下是详细的示例说明:

import pandas as pd

# 示例数据
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob', 'Charlie'],
    'Subject': ['Math', 'Math', 'Math', 'Science', 'Science', 'Science'],
    'Score': [85, 90, 88, 92, 95, 89],
    'Age': [20, 22, 21, 20, 22, 21]
}

df = pd.DataFrame(data)

# 自定义聚合函数1:计算每组的总分和平均分
def custom_agg1(group):
    return {
        'Total_Score': group['Score'].sum(),
        'Average_Score': group['Score'].mean(),
        'Count': len(group)
    }

# 对"Name"和"Subject"两列进行分组,并应用聚合函数
grouped1 = df.groupby(['Name', 'Subject']).apply(custom_agg1).reset_index()
print(grouped1)

# 示例输出:
#        Name Subject  Total_Score  Average_Score  Count
# 0     Alice    Math           85           85.0      1
# 1     Alice Science           92           92.0      1
# 2       Bob    Math           90           90.0      1
# 3       Bob Science           95           95.0      1
# 4  Charlie    Math           88           88.0      1
# 5  Charlie Science           89           89.0      1


# 自定义聚合函数2:返回每组中分数最高和最低的记录
def custom_agg2(group):
    return {
        'Max_Score': group['Score'].max(),
        'Min_Score': group['Score'].min(),
        'Age_Range': group['Age'].max() - group['Age'].min()
    }

# 使用`agg`方法
aggregations = {
    'Score': ['max', 'min'],
    'Age': lambda x: x.max() - x.min()
}

grouped2 = df.groupby(['Name', 'Subject']).agg(aggregations)
grouped2.columns = ['Max_Score', 'Min_Score', 'Age_Range']
print(grouped2)

# 示例输出:
#                    Max_Score  Min_Score  Age_Range
# Name   Subject                                   
# Alice  Math               85         85          0
#        Science            92         92          0
# Bob    Math               90         90          0
#        Science            95         95          0
# Charlie Math               88         88          0
#        Science            89         89          0


# 自定义聚合函数3:综合计算每组的总分和年龄的平均值
def custom_agg3(group):
    total_score = group['Score'].sum()
    avg_age = group['Age'].mean()
    return pd.Series({
        'Total_Score': total_score,
        'Avg_Age': avg_age
    }, name='Metrics')

# 使用`agg`方法
aggregations = {
    'Score': 'sum',
    'Age': 'mean'
}

grouped3 = df.groupby(['Name', 'Subject']).agg(aggregations)
grouped3.columns = ['Total_Score', 'Avg_Age']
print(grouped3)

# 示例输出:
#                    Total_Score  Avg_Age
# Name   Subject                        
# Alice  Math                 85     20.0
#        Science              92     20.0
# Bob    Math                 90     22.0
#        Science              95     22.0
# Charlie Math                 88     21.0
#        Science              89     21.0


# 总结:
# 1. `apply`方法适用于需要返回复杂结构的自定义函数,但可能效率较低。
# 2. `agg`方法适用于简单的聚合操作,性能较高。
# 3. 可以根据需求选择适合的方法,或者结合使用两者。

这段代码展示了如何通过多种方式在Pandas中对多个列进行分组并应用自定义聚合函数。从简单的统计计算到复杂的自定义逻辑,Pandas提供了灵活的操作方式。