Pandas数据帧到字典,值为列表

时间:2016-06-24 20:36:28

标签: python pandas

我们有以下数据框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}}

2 个答案:

答案 0 :(得分:3)

设置索引后,进行转置,然后将to_dictorient='list'一起使用:

df.set_index([0,1]).T.to_dict(orient='list')

结果输出:

{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}

答案 1 :(得分:1)

尝试:

Wall
相关问题