【问题标题】:Creating a heatmap from a list of nested dictionaries in python从python中的嵌套字典列表创建热图
【发布时间】:2020-05-31 18:43:45
【问题描述】:

我对 python 还是很陌生,目前我一直在写一个热图来比较不同语言的词向量。

我的数据是这样的:

data = [{'de':  {'de': [[1]], 'es': [[0.9644323]], 'fr': [[0.9419257]], 'hu': [[0.9297902]]}},
        {'fr':   {'fr': [[1]], 'de': [[0.9419257]], 'es': [[0.9382719]], 'hu': [[0.91247433]]}},
        {'hu':  {'hu': [[1]], 'de': [[0.9419257]], 'es': [[0.9382719]], 'fr': [[0.91247433]]}}]

数据显示了一种语言中的短语与其翻译之间的相似性(例如,在第一本词典中,我有一个德语短语,我将其与 ES、HU 和 FR 的翻译进行比较)。我想为这个嵌套字典列表提供一个热图。如何在热图中可视化它?我尝试在 seaborn 中查看热图,但对我的字典是嵌套的事实感到困惑。

【问题讨论】:

    标签: python dictionary seaborn visualization heatmap


    【解决方案1】:

    如果快速解决。您首先使用字典将列表转换为数据框,然后使用 seaborn 的热图绘制它。不过,我相信还有更优雅的解决方案。

    import pandas as pd
    import seaborn as sns
    %matplotlib inline
    
    frames = []
    
    for d in data:
        frames.append(pd.DataFrame.from_dict(d, orient='index'))
    
    res = pd.concat(frames)
    res = res.applymap(lambda x: x[0][0])
    sns.heatmap(res, annot=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 2021-04-04
      • 2021-11-20
      相关资源
      最近更新 更多