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
相关产品推荐
相关产品推荐

