We have the following dataframe df,
0 1 2 3
0 'a' 'b' 1 2
1 'a' 'c' 2 4
I want output as
{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
How to use .to_dict() to generate the output?
I tried
df.set_index([0,1])[[2,3]].to_dict()
and get the result
{2: {('a', 'b'): 1, ('a', 'c'): 2}, 3: {('a', 'b'): 2, ('a', 'c'): 4}}
After setting the index, take the transpose and then use to_dict
with orient='list'
:
df.set_index([0,1]).T.to_dict(orient='list')
The resulting output:
{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
Try:
{k: v.tolist() for k, v in df.set_index([0, 1]).iterrows()}
{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.