Reputation: 31
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:
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. So like:
{('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. Thank you in advance.
Upvotes: 2
Views: 233
Reputation: 35646
Let's try stack then 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
:
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
:
{('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}
Upvotes: 4