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

Pandas DataFrame集合列用seaborn绘图报unhashable type: 'set'如何解决

错误原因

set属于不可哈希的可变类型,无法作为分组统计的键,也不能作为seaborn绘图的分类维度,因此会触发类型错误。转换为可哈希的类型后即可正常处理。

解决步骤

1. 转换集合列类型

将集合列转换为排序后元组(避免相同元素的集合因顺序问题被判定为不同分类),如果需要x轴显示集合样式的标签,也可以转换为字符串格式:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 构造示例DataFrame
df = pd.DataFrame([['Alex',{33, 34}],['Bob',{33}],['Clarke',{33, 34}]], columns = ['names', 'indicators'])

# 方案1:转排序后元组,保留数据结构
df['indicators'] = df['indicators'].apply(lambda x: tuple(sorted(x)))

# 方案2:转字符串,x轴直接显示集合样式标签
# df['indicators'] = df['indicators'].apply(lambda x: str(set(sorted(x))))

2. 统计频率

直接调用value_counts即可得到预期统计结果:

print(df['indicators'].value_counts())
"""
输出结果:
(33, 34)    2
(33,)       1
Name: indicators, dtype: int64
"""

3. 绘制统计图

两种可选绘图方式:

  • 直接使用countplot对原始数据计数绘图:
sns.countplot(data=df, x='indicators')
plt.show()
  • 先统计频率再用barplot绘图,适合大数据量场景:
count_df = df['indicators'].value_counts().reset_index()
count_df.columns = ['indicator_combination', 'count']
sns.barplot(data=count_df, x='indicator_combination', y='count')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 14:24:02