You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算每个subid的SG课程均值并对A课程观测值做差值运算?

高效实现按subid计算SG课程均值并与A课程performance做差

需求回顾

  1. 对每个subid,计算其对应SG课程的performance均值
  2. 用该均值减去同subid下A课程的每一项performance值

数据修正说明

原代码里列名存在拼写错误:peformance需改为performance,否则后续操作会报错,先修正这个问题。

简洁实现方法

方法一:分组均值+索引映射(高效)

import pandas as pd

# 原数据定义(修正列名拼写)
sectionIndex = [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10]
subid = [1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2]
course = ['A','A','A','A','A','A','A','A','SG','SG', 'A','A','A','A','A','A','A','A','SG','SG']
performance = [3,6,1,6,5,6,7,8,9,13,1,2,3,3,4,4,6,3,1,10]
ddict = {
    'subid': subid,
    'sectionIndex': sectionIndex,
    'course': course,
    'performance': performance
}

df = pd.DataFrame(ddict)

# 1. 计算每个subid的SG课程performance均值
sg_mean = df[df['course'] == 'SG'].groupby('subid')['performance'].mean()

# 2. 筛选A课程数据,映射对应均值并计算差值
a_course_data = df[df['course'] == 'A'].copy()
a_course_data['sg_mean_minus_a_perf'] = sg_mean.loc[a_course_data['subid']].values - a_course_data['performance']

print(a_course_data)

方法二:分组均值表+合并(直观)

如果觉得索引映射不够直观,可使用merge方式实现:

# 生成SG均值表,保留subid作为普通列
sg_mean_df = df[df['course'] == 'SG'].groupby('subid', as_index=False)['performance'].mean().rename(columns={'performance': 'sg_mean'})

# 合并A课程数据与均值表,计算差值
result = df[df['course'] == 'A'].merge(sg_mean_df, on='subid')
result['sg_mean_minus_a_perf'] = result['sg_mean'] - result['performance']

print(result)

结果验证

  • subid=1的SG课程performance为9和13,均值为11,对应A课程的差值为11 - 对应performance值(如11-3=8、11-6=5等)
  • subid=2的SG课程performance为1和10,均值为5.5,对应A课程的差值为5.5 - 对应performance值(如5.5-1=4.5、5.5-2=3.5等)

内容的提问来源于stack exchange,提问作者Cmagelssen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:35:26