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

pandas groupby().apply报错‘DataFrame不可哈希’的解决方法咨询

解决pandas groupby.apply报错TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed

这个错误的核心原因很直接:你传给groupby.apply()的right_top是一个DataFrame对象,但apply方法需要的是一个可调用的函数,而不是一个可变的DataFrame。pandas尝试把right_top当作函数来处理时,因为DataFrame是可变的不能被哈希,所以抛出了这个错误。

要解决这个问题,你需要先明确你想用right_top对每个分组做什么操作,然后把这个操作封装成一个函数,再传给apply。下面举几个常见场景的解决方案:

场景1:将每个分组与right_top合并

如果你想把每个exam_id分组的DataFrame和right_top按某列合并(比如共同的id列),可以定义这样的函数:

import pandas as pd

def merge_group_with_right_top(group):
    # 这里假设按'id'列合并,你可以根据实际业务调整合并键和方式
    return pd.merge(group, right_top, on='id', how='inner')

# 调用apply时传入这个函数
g = right_df.groupby('exam_id').apply(merge_group_with_right_top)
print(g)

场景2:筛选每个分组中存在于right_top的行

如果你的需求是从每个分组里筛选出在right_top中存在的记录(比如根据学生id匹配),可以这样写:

def filter_group_with_right_top(group):
    # 示例:筛选分组中student_id在right_top的student_id列表里的行
    return group[group['student_id'].isin(right_top['student_id'])]

g = right_df.groupby('exam_id').apply(filter_group_with_right_top)
print(g)

场景3:关联分组与right_top的聚合结果

如果right_top是每个exam_id的聚合统计结果(比如最高分、平均分),其实不需要用apply,直接用merge更高效:

# 假设right_top包含exam_id和对应的统计列(比如top_score)
g = pd.merge(right_df, right_top, on='exam_id', how='left')
print(g)

总结一下:先理清你要对每个分组执行的具体逻辑,把逻辑写成函数,再传给groupby.apply——别直接把DataFrame塞进去就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:16:08