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

如何基于student_id分组,按规则生成error_flag_type列?

按student_id分组创建error_flag_type列的实现方案

问题描述

如何按student_id分组,创建新列error_flag_type,其值由分组内subject_id和error字段的特征决定?

原始数据样例

student_idsubject_iderrorteam
11yesA
12A
13A
1yesA
24B
25B
2yesB
36B
37B
38B
39yesB
410A
411A
412A

分组标记规则

  • 若student_id分组内同时存在:subject_id非空且error为yes、subject_id为空且error为yes的行,error_flag_type标记为both;
  • 若分组内仅存在:subject_id为空且error为yes的行,error_flag_type标记为student_id_level;
  • 若分组内仅存在:subject_id非空且error为yes的行,error_flag_type标记为subject_id_level;
  • 若分组内无error为yes的行,error列值设为no_error,error_flag_type标记为no_error;

实现代码(Python Pandas)

import pandas as pd

# 构造原始数据(实际场景可替换为pd.read_csv等读取方式)
df = pd.DataFrame({
    'student_id': [1,1,1,1,2,2,2,3,3,3,3,4,4,4],
    'subject_id': [1,2,3,pd.NA,4,5,pd.NA,6,7,8,9,10,11,12],
    'error': ['yes', pd.NA, pd.NA, 'yes', pd.NA, pd.NA, 'yes', pd.NA, pd.NA, pd.NA, 'yes', pd.NA, pd.NA, pd.NA],
    'team': ['A','A','A','A','B','B','B','B','B','B','B','A','A','A']
})

# 定义分组逻辑函数
def get_error_flag(group):
    error_yes = group[group['error'] == 'yes']
    if error_yes.empty:
        return pd.Series({'error': 'no_error', 'error_flag_type': 'no_error'})
    
    has_subj_error = not error_yes[error_yes['subject_id'].notna()].empty
    has_stu_error = not error_yes[error_yes['subject_id'].isna()].empty
    
    if has_subj_error and has_stu_error:
        flag = 'both'
    elif has_stu_error:
        flag = 'student_id_level'
    else:
        flag = 'subject_id_level'
    
    return pd.Series({'error': 'yes', 'error_flag_type': flag})

# 应用分组并聚合结果
final_result = df.groupby(['student_id', 'team'], as_index=False).apply(get_error_flag).reset_index(drop=True)
print(final_result)

最终汇总结果

student_idteamerrorerror_flag_type
1Ayesboth
2Byesstudent_id_level
3Byessubject_id_level
4Ano_errorno_error

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:39:21