[英]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![]() |
City2![]() |
City3![]() |
|
---|---|---|---|
City1![]() |
0 ![]() |
2.2 ![]() |
3.1 ![]() |
City2![]() |
2.1 ![]() |
0 ![]() |
4.0 ![]() |
City3![]() |
3.2 ![]() |
4.3 ![]() |
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.