简体   繁体   English

从 python 中的嵌套字典列表创建热图

[英]Creating a heatmap from a list of nested dictionaries in python

I'm pretty new to python, and currently I'm stuck with writing a heatmap for comparing word vectors for different languages.我对 python 很陌生,目前我一直坚持编写热图来比较不同语言的词向量。

The data I have looks like this:我拥有的数据如下所示:

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]]}}]

The data shows similarity between the phrase in one language to its translations (eg in the first dictionary I have a German phrase that I compare to ES, HU and FR translations).数据显示了一种语言中的短语与其翻译之间的相似性(例如,在第一本词典中,我有一个德语短语,我将其与 ES、HU 和 FR 翻译进行比较)。 I would like to have one heatmap for this list of nested dictionaries.我想为这个嵌套字典列表提供一个热图。 How do I visualise it in a heatmap?如何在热图中可视化它? I tried looking at heatmaps in seaborn, but was confused by the fact my dictionary is nested.我尝试查看 seaborn 中的热图,但对我的字典嵌套的事实感到困惑。

If solving quickly.如果快速解决。 You first transform your list with dictionaries to dataframe and then plot it with seaborn's heatmap.您首先使用字典将列表转换为 dataframe,然后使用 seaborn 的热图将其转换为 plot。 I am sure there could be more elegant solutions, however.但是,我相信可能会有更优雅的解决方案。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM