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

Pandas透视表报错:Unhashable type 'list' 问题求助

问题解决:Pandas透视表报错Unhashable type 'list'及实现预期效果

错误原因

  1. 不可哈希值问题:Fruit grown列中存在列表类型的值,而透视表的行/列索引要求元素是可哈希类型(如字符串、数值),列表属于不可哈希类型,直接使用会触发报错。
  2. 参数使用错误:你编写的pivot_table参数完全不符合语法要求,没有指定正确的行索引、列索引和要聚合的数值列。

解决步骤

1. 清理Fruit grown列,转为可哈希的字符串类型

根据数据实际情况二选一:

  • 如果单元格是列表类型(如["Other Fruits"]):
final_df2['Fruit grown'] = final_df2['Fruit grown'].apply(lambda x: x[0] if isinstance(x, list) else x)
  • 如果单元格是带[]的字符串(如Other Fruits[]):
final_df2['Fruit grown'] = final_df2['Fruit grown'].str.replace(r'\[]', '', regex=True)

2. 正确生成透视表

指定透视表的行索引、列索引、数值列及聚合函数(因每个国家-水果组合只有一行数据,用sum或first均可):

df3 = final_df2.pivot_table(
    index='Country',
    columns='Fruit grown',
    values='Prod(Tonnes)',
    aggfunc='sum'
)
# 优化格式,贴近预期效果
df3.columns.name = 'Fruits'
df3 = df3.reset_index()

执行后得到的结果:

Fruits Country  Apples  Oranges  Other Fruits
0          USA     100       50            60
1        India     200       50            50

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:01:20