数据帧到字典转换

时间:2017-01-08 14:33:43

标签: python pandas dataframe

我关注Dataframe

     image          product  vp_fk               mask
0    136524         105       2316               51322
1    136524         105       2316               51324
2    136524         106       2316               51325
3    136524         106       2316               51328
4    136524         106       2316               51329
5    136525         108       2319               51330

我想将其转换为以下字典:

{105:[[136524, 2316, 51322], 
      [136524, 2316, 51324]]
106: [[136524, 2316, 51325], 
      [136524, 2316, 51328],
      [136524, 2316, 51329]]
108: [[136525, 2319, 51330]]}

1 个答案:

答案 0 :(得分:4)

试试这个:

In [187]: df.groupby('product')[['image','vp_fk','mask']].apply(lambda grp: grp.values.tolist()).to_dict()
Out[187]:
{105: [[136524, 2316, 51322], [136524, 2316, 51324]],
 106: [[136524, 2316, 51325], [136524, 2316, 51328], [136524, 2316, 51329]],
 108: [[136525, 2319, 51330]]}