Reputation: 33
I want to convert a dataframe to a dictionary where the key is the row index and the column name of the dataframe and each key's value is the location of each row index and column name.
Let's assume this is my dataframe.
1 2 3
0 1 2 3
1 4 5 6
2 7 8 9
I want my dictionary to look something like this:
((0, 1), 1)
((0, 2), 2)
((0, 3), 3)
((1, 1), 4)
How can I achieve this?
Upvotes: 0
Views: 632
Reputation: 862671
Use stack
for MultiIndex Series
with to_dict
:
d = df.stack().to_dict()
print (d)
{(0, 1): 1, (0, 2): 2, (0, 3): 3,
(1, 1): 4, (1, 2): 5, (1, 3): 6,
(2, 1): 7, (2, 2): 8, (2, 3): 9}
But if want tuple
s:
s = df.stack()
L = list(zip(s.index.tolist(), s))
print (L)
[((0, 1), 1), ((0, 2), 2), ((0, 3), 3),
((1, 1), 4), ((1, 2), 5), ((1, 3), 6),
((2, 1), 7), ((2, 2), 8), ((2, 3), 9)]
Upvotes: 3