简体   繁体   English

如何将不对称的成对距离矩阵转换为字典?

[英]How to convert an asymmetric pairwise distance matrix to dictionary?

I've distance matrix which I want to convert to a dict with two keys and one value.我有距离矩阵,我想将其转换为具有两个键和一个值的字典。 My csv file looks something like this:我的 csv 文件看起来像这样:

City1城市1 City2城市2 City3城市3
City1城市1 0 0 2.2 2.2 3.1 3.1
City2城市2 2.1 2.1 0 0 4.0 4.0
City3城市3 3.2 3.2 4.3 4.3 0 0

And I imported my csv file as a pandas data frame with pd.read_csv and now I want to convert this data frame to a dictionary which should use the first column and the first row as keys and the rest as values.我将我的 csv 文件作为 pandas 数据框与 pd.read_csv 导入,现在我想将此数据框转换为字典,该字典应使用第一列和第一行作为键,并将 Z65E8800B5C6800AAD896F88 用作值。 So like:就像:

{('City1','City1'): 0, ('City1','City2'): 2.1, ('City1','City3'): 3.2, ...} {('City1','City1'): 0, ('City1','City2'): 2.1, ('City1','City3'): 3.2, ...}

I tried to use pandas.to_dict function but I wasn't able to figure out how to tell this function to not only use the column names as the keys.我尝试使用 pandas.to_dict function 但我无法弄清楚如何告诉这个 function 不仅使用列名作为键。 Thank you in advance.先感谢您。

Let's try stack then to_dict:让我们尝试堆栈然后 to_dict:

import pandas as pd

df = pd.DataFrame({
    'City1': {'City1': 0, 'City2': 2.1, 'City3': 3.2},
    'City2': {'City1': 2.2, 'City2': 0.0, 'City3': 4.2},
    'City3': {'City1': 3.1, 'City2': 4.0, 'City3': 0},
})

d = df.stack().to_dict()
print(d)

df : df

       City1  City2  City3
City1    0.0    2.2    3.1
City2    2.1    0.0    4.0
City3    3.2    4.2    0.0

d : d

{('City1', 'City1'): 0.0, ('City1', 'City2'): 2.2, ('City1', 'City3'): 3.1,
 ('City2', 'City1'): 2.1, ('City2', 'City2'): 0.0, ('City2', 'City3'): 4.0,
 ('City3', 'City1'): 3.2, ('City3', 'City2'): 4.2, ('City3', 'City3'): 0.0}

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

相关问题 Python-如何生成成对汉明距离矩阵 - Python - How to generate the Pairwise Hamming Distance Matrix 如何计算GPU上的成对距离矩阵 - How to calculate pairwise distance matrix on the GPU 将成对距离的长格式数据帧转换为python中的距离矩阵 - Convert long-form dataframe of pairwise distances to distance matrix in python 如何在python中使用广播计算矩阵的成对余弦距离 - How to calculate pairwise cosine distance of matrix using broadcasting in python pytorch 如何计算矩阵成对距离? 为什么“自我”距离不为零? - How does pytorch calculate matrix pairwise distance? Why isn't 'self' distance not zero? 如何使用自定义度量(设置距离)构造成对距离矩阵? - How can I construct a pairwise distance matrix using a custom metric (set distance)? 在 Python 中计算加权成对距离矩阵 - Calculate weighted pairwise distance matrix in Python 分层聚类预先计算距离的成对距离矩阵 - Hierarchical clustering a pairwise distance matrix of precomputed distances pandas:将距离矩阵转换为字典,其中元素按邻近度排序 - pandas: Convert a distance matrix into a dictionary with the elements sorted by proximity 如何在python中将字典转换为矩阵? - How to convert dictionary to matrix in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM