我们有以下数据框df,
0 1 2 3
0 'a' 'b' 1 2
1 'a' 'c' 2 4
我希望输出为
{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
如何使用.to_dict()生成输出?
我试过
df.set_index([0,1])[[2,3]].to_dict()
并获得结果
{2: {('a', 'b'): 1, ('a', 'c'): 2}, 3: {('a', 'b'): 2, ('a', 'c'): 4}}
答案 0 :(得分:3)
设置索引后,进行转置,然后将to_dict
与orient='list'
一起使用:
df.set_index([0,1]).T.to_dict(orient='list')
结果输出:
{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
答案 1 :(得分:1)
尝试:
Wall