如何对分组后的多列数据应用自定义函数并生成结果列?
按行业分组给股票Growth值打分的实现方案
修正原代码并实现核心功能
首先修正原代码的语法错误(缺少闭合括号),然后通过分组聚合+广播的方式实现按行业均值打分的需求:
import numpy as np import pandas as pd # 读取Excel数据(修正原代码的语法错误) data = pd.read_excel('dummydata.xlsx') # 计算每个行业的Growth均值,并将结果广播到对应行业的每一行 data['Industry_Growth_Mean'] = data.groupby('Industry')['Growth'].transform('mean') # 定义打分函数:低于行业均值打5分,高于则打10分 def score(row): return 5 if row['Growth'] < row['Industry_Growth_Mean'] else 10 # 生成得分列,或直接获取期望的列表 data['Score'] = data.apply(score, axis=1) score_list = data['Score'].tolist() print(score_list) # 输出符合预期的 [5, 10, 10, 5, 10, 5]
关键逻辑说明
直接对data['Growth'].apply(score)无法实现需求,因为单个值的apply无法获取该值所属行业的聚合信息。通过groupby.transform可以将分组计算的均值广播到每一行,让每条数据都能直接拿到自己所在行业的均值,再进行比较打分。
扩展方案
1. 扩展到其他列
只需替换代码中的列名即可,比如针对Profit列打分:
data['Industry_Profit_Mean'] = data.groupby('Industry')['Profit'].transform('mean') def score_profit(row): return 5 if row['Profit'] < row['Industry_Profit_Mean'] else 10 data['Profit_Score'] = data.apply(score_profit, axis=1)
2. 替换聚合条件(分位数/百分位数)
将transform的聚合逻辑替换为分位数计算即可,比如用75分位数作为阈值:
# 计算每个行业Growth的75分位数 data['Industry_Growth_75th'] = data.groupby('Industry')['Growth'].transform(lambda x: x.quantile(0.75)) # 基于75分位数调整打分逻辑 def score_quantile(row): return 5 if row['Growth'] < row['Industry_Growth_75th'] else 10 data['Score_75th'] = data.apply(score_quantile, axis=1)
内容的提问来源于stack exchange,提问作者noviceprogramer
相关产品推荐
相关产品推荐

