【问题标题】:Plotting sets from Pandas df and Type Error unhashable type: 'set'从 Pandas df 和 Type Error unhashable type 中绘制集合:'set'
【发布时间】:2021-08-27 03:13:34
【问题描述】:

我有一个包含一列集合的数据框:

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

我想绘制 df['indicators'] 中值的频率,以了解发生了哪些指标组合。即,在这里我想要一个显示 {33, 34} 出现两次而 {33} 出现一次的图。让seaborn成为某人,我通常会做一个直方图:

sb.countplot(data = df, x = 'indicators')

但是当我尝试这个时,我得到 TypeError: unhashable type: 'set'。我尝试将参数从集合转换为列表或 np.array() 无济于事。

【问题讨论】:

    标签: python pandas plot seaborn typeerror


    【解决方案1】:
    import seaborn as sns
    

    通过astype()尝试:

    sns.countplot(data = df.astype({'indicators':'str'}), x = 'indicators')
    #the 'indicators' column in you real dataset won't change
    

    df['indicators']=df['indicators'].astype(str)
    #Finally:
    sns.countplot(data = df, x = 'indicators')
    #For making back the the 'indicators' column back to set you can use:
    df['indicators']=df['indicators'].str.strip('{}').str.split(',').map(set)
    

    输出:

    【讨论】:

    • 这不是我想要的。我正在尝试查看哪些指标相互显示,所以我想要一个显示 {33, 34} 的频率为 2 且 {33} 的频率为 1 的图。您已经表明 {33} 有一个频率3 和 {34} 的频率为 2。
    • @shaha 更新答案...请看一下:)
    • 谢谢。 :) 这也是我现在想通的。我不希望将所有内容都变成字符串,因为这样可以减少可变性,尽管它有效!我暂时赞成您的评论,如果在接下来的几个小时内没有其他人可以直接回答,我会接受。
    • 也更新了答案...请看一下:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2019-06-06
    • 2012-11-07
    • 2021-08-31
    相关资源
    最近更新 更多