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

如何基于另一DataFrame为当前DataFrame每行统计学生类别数量?

解决方法:关联数据集并按行统计学生类别数量

首先,你的思路方向是对的——先建立学生到类别的映射,但缺少了按行统计各类别数量的关键步骤。我们可以分几步来实现需求:

步骤1:建立学生姓名到类别的映射

先从DataFrame2中提取Name到Category的对应关系,用字典存储会更方便后续替换:

# 假设你的DataFrame2命名为df_scores,DataFrame1命名为df_batches
category_map = df_scores.set_index('Name')['Category'].to_dict()

步骤2:将批次数据替换为对应类别

把df_batches里的每个学生姓名替换成他们的类别:

df_categories = df_batches.replace(category_map)

这一步之后,df_categories的内容会变成:

s1s2s3
GoodAverageGood
AveragePoorGood
GoodGoodPoor

步骤3:按行统计各类别数量

接下来对每行做类别计数,并且要确保所有目标类别(Good、Average、Poor)都出现在结果中,缺失的补0:

counts = df_categories.apply(lambda row: row.value_counts().reindex(['Good', 'Average', 'Poor'], fill_value=0), axis=1)

这里用apply(axis=1)逐行处理,value_counts()统计每行的类别出现次数,reindex用来补全所有需要的类别并填充0。

步骤4:合并原数据和统计结果

最后把统计结果和原df_batches合并,得到你要的最终输出:

final_df = pd.concat([df_batches, counts], axis=1)

完整代码示例

把所有步骤整合起来,完整代码如下:

import pandas as pd

# 构造示例数据
df_batches = pd.DataFrame({
    's1': ['Stud1', 'Stud2', 'Stud1'],
    's2': ['Stud2', 'Stud4', 'Stud3'],
    's3': ['Stud3', 'Stud1', 'Stud4']
})

df_scores = pd.DataFrame({
    'Name': ['Stud1', 'Stud2', 'Stud3', 'Stud4'],
    'Point': [90, 80, 95, 55],
    'Category': ['Good', 'Average', 'Good', 'Poor']
})

# 执行步骤
category_map = df_scores.set_index('Name')['Category'].to_dict()
df_categories = df_batches.replace(category_map)
counts = df_categories.apply(lambda row: row.value_counts().reindex(['Good', 'Average', 'Poor'], fill_value=0), axis=1)
final_df = pd.concat([df_batches, counts], axis=1)

print(final_df)

运行后就会得到你期望的输出结果:

s1s2s3GoodAveragePoor
Stud1Stud2Stud3210
Stud2Stud4Stud1111
Stud1Stud3Stud4201

为什么你的原代码没生效?

你原来的代码df5.join(df5.replace(s).add_prefix('Type_'))只是把每个学生替换成类别并添加前缀,但没有做统计计数的操作,所以只会得到每行的类别列,而不是各类别的数量。我们上面的步骤补上了这个关键环节,就可以得到正确的统计结果啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:22:58