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

使用Pandas单行DataFrame值作为字典键访问值时的类型错误解决

解决Pandas判断时的TypeError问题

错误原因

sample_df['Type']返回的是Pandas Series对象,而字典的键要求是可哈希的标量类型(比如字符串、数字)。Series是可变容器,无法被哈希,所以用它当字典键时会触发TypeError: 'Series' objects are mutable, thus they cannot be hashed错误。

解决方法

因为你明确说明sample_df只有一行数据,这里提供两种实用的处理方式:

方式1:直接提取标量值

既然只有一行,直接把Series转成单个标量就能正常当字典键使用:

# 用iloc[0]提取标量
if sample_df['Cost'].iloc[0] <= capacity[sample_df['Type'].iloc[0]]:
    # 此处编写你的判断逻辑

或者用.values[0]也能拿到标量:

if sample_df['Cost'].values[0] <= capacity[sample_df['Type'].values[0]]:
    # 此处编写你的判断逻辑

方式2:用Pandas映射方法(兼容多行场景)

如果后续代码可能扩展到处理多行数据,推荐用map方法把字典映射成新列,再做判断:

# 把capacity映射为新列
sample_df['Capacity'] = sample_df['Type'].map(capacity)
# 单行数据用all()或any()都可以,多行时按需选择
if (sample_df['Cost'] <= sample_df['Capacity']).all():
    # 此处编写你的判断逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:40:37