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

如何用Pandas分组高中成绩单数据并为每组插入标题行?

解决方案

实现思路

通过groupby按sname、year、term分组,为每个分组生成包含分组信息的标题行,再将所有分组数据合并,最终只保留mark和course列。

示例代码

import pandas as pd

# 构建示例数据集
data = {
    'sname': ['school1', 'school1', 'school1', 'school2', 'school2', 'school3'],
    'year': ['2020-2021', '2020-2021', '2020-2021', '2021-2022', '2021-2022', '2021-2022'],
    'term': [1, 1, 1, 2, 2, 2],
    'mark': ['F', 'F', 'D', 'B-', 'C-', 'F'],
    'course': ['Class1', 'Class2', 'Class3', 'Class4', 'Class5', 'Class6']
}
df = pd.DataFrame(data)

# 定义处理单个分组的函数
def add_group_header(group):
    # 生成分组标题文本
    header_content = f"{group['year'].iloc[0]} term {group['term'].iloc[0]} {group['sname'].iloc[0]}"
    # 创建标题行的DataFrame
    header_df = pd.DataFrame({'mark': [header_content], 'course': ['']})
    # 合并标题行与当前分组的目标列数据
    return pd.concat([header_df, group[['mark', 'course']]], ignore_index=True)

# 分组处理并合并结果
final_result = df.groupby(['sname', 'year', 'term'], group_keys=False).apply(add_group_header)

# 打印输出结果
print(final_result.to_string(index=False))

最终输出效果

mark  course
2020-2021 term 1 school1        
                     F  Class1
                     F  Class2
                     D  Class3
2021-2022 term 2 school2        
                    B-  Class4
                    C-  Class5
2021-2022 term 2 school3        
                     F  Class6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:02:22