如何基于student_id分组,按规则生成error_flag_type列?
按
student_id分组创建error_flag_type列的实现方案 问题描述
如何按student_id分组,创建新列error_flag_type,其值由分组内subject_id和error字段的特征决定?
原始数据样例
| student_id | subject_id | error | team |
|---|---|---|---|
| 1 | 1 | yes | A |
| 1 | 2 | A | |
| 1 | 3 | A | |
| 1 | yes | A | |
| 2 | 4 | B | |
| 2 | 5 | B | |
| 2 | yes | B | |
| 3 | 6 | B | |
| 3 | 7 | B | |
| 3 | 8 | B | |
| 3 | 9 | yes | B |
| 4 | 10 | A | |
| 4 | 11 | A | |
| 4 | 12 | A |
分组标记规则
- 若
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_id | team | error | error_flag_type |
|---|---|---|---|
| 1 | A | yes | both |
| 2 | B | yes | student_id_level |
| 3 | B | yes | subject_id_level |
| 4 | A | no_error | no_error |
内容的提问来源于stack exchange,提问作者fast_crawler
相关产品推荐
相关产品推荐

