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

如何用Python和Pandas按课程单元分组生成汇总表格?

最优解决方案:利用Pandas Groupby实现问卷分组汇总

直接用Pandas的groupby结合内置统计方法,比手动while循环高效得多,代码也更简洁易维护。以下是完整实现步骤:

步骤说明

  1. 固定响应选项的顺序,确保输出表格的列顺序统一;
  2. 按CourseCode和Unit分组,对每个分组内的问题列做占比统计;
  3. 补全缺失的响应选项(填充0%),最后整理成目标格式的表格。

完整代码

import pandas as pd

# 假设你的问卷数据已读入为DataFrame df
df = pd.DataFrame({
    'CourseCode': [3300, 3300, 3200, 3100, 3300],
    'Unit': [1, 2, 2, 1, 2],
    'Q1contentxxx': ['StronglyAgree', 'StronglyDisagree', 'Agree', 'Agree', 'Disagree'],
    'Q2contentyyy': ['Agree', 'Neutral', 'Disagree', 'Disagree', 'Neutral'],
    'Q3contentsss': ['Neutral', 'Disagree', 'Neutral', 'Neutral', 'Disagree'],
    'Q4contentddd': ['StronglyAgree', 'StronglyDisagree', 'Agree', 'Agree', 'Disagree'],
    'Q5contentfff': ['Agree', 'Neutral', 'Disagree', 'Disagree', 'Neutral'],
    'Q6contentggg': ['Neutral', 'Disagree', 'Neutral', 'Neutral', 'Disagree']
})

# 定义固定的响应选项顺序,确保输出列一致
response_options = ['StronglyAgree', 'Agree', 'Neutral', 'Disagree', 'StronglyDisagree']

# 按课程+单元分组处理
for (course_code, unit), group_data in df.groupby(['CourseCode', 'Unit']):
    print(f"### 课程单元 {course_code}-{unit}")
    
    # 初始化存储每个问题的统计结果
    question_stats = {}
    # 遍历所有问题列(跳过前两列标识列)
    for question_col in df.columns[2:]:
        # 统计当前问题各选项的占比,normalize=True直接得到比例
        option_pct = group_data[question_col].value_counts(normalize=True)
        # 补全所有响应选项,缺失的填充0,保证列完整
        option_pct = option_pct.reindex(response_options, fill_value=0)
        # 转换为百分比字符串格式
        question_stats[question_col] = [f"{round(pct * 100)}%" for pct in option_pct.values]
    
    # 转换为目标格式的DataFrame
    summary_table = pd.DataFrame(question_stats).T.reset_index()
    summary_table.columns = ['Question'] + response_options
    
    # 输出Markdown格式的表格
    print(summary_table.to_markdown(index=False))
    print("\n")

代码优势

  • 避免手动逐行迭代,利用Pandas向量化操作,数据量大时效率提升明显;
  • 自动处理分组逻辑,无需手动判断每个课程单元的范围;
  • 通过reindex保证所有响应选项都出现在结果中,不会遗漏0%的情况;
  • 代码结构清晰,后续新增问题列或调整选项时只需修改对应列表即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:16:25