使用groupby将数据帧转换为dict

时间:2019-04-26 06:12:54

标签: python python-3.x pandas

我有一个数据框

df = pd.DataFrame({'a':[1,1,1,2,2,3], 'b':['a','a','a','b','b','c'],
                   'c':['qw','sw','aw','ew','rw','qw'],'d':['cv','fv','gv','bv','nb','fv']})

我想将其转换为dict,如下所示:

{
 {'a':1,'b':'a', 'xyz':[{'c': 'qw', 'd': 'cv'},{'c': 'sw', 'd': 'fv'}, {'c':'aw','d':'gv'}]},
 {'a':2 'b':'b', 'xyz':[{'c': 'ew', 'd': 'bv'}, {'c': 'rw', 'd': 'nb'}]},
 {'a':3 'b':'c', 'xyz':[{'c': 'qw', 'd': 'fv'}]}
}

我的努力:

df['xyz'] = df[['c','d']].to_dict(orient='records')

df = df.groupby(['a','b'])['xyz'].apply(lambda x: x.tolist()).reset_index(drop=True)

print(df.to_dict())

哪个给我输出:

{0: [{'d': 'cv', 'c': 'qw'}, {'d': 'fv', 'c': 'sw'}, {'d': 'gv', 'c': 'aw'}], 
 1: [{'d': 'bv', 'c': 'ew'}, {'d': 'nb', 'c': 'rw'}], 
 2: [{'d': 'fv', 'c': 'qw'}]} 

1 个答案:

答案 0 :(得分:3)

我认为您需要DataFrame.to_dictrecords

df1 = (df.groupby(['a','b'])['c','d']
         .apply(lambda x: x.to_dict(orient='records'))
         .reset_index(name='xyz'))

d = df1.to_dict(orient='records')
print (d)

[{'a':1,'b':'a','xyz':[{'c':'qw','d':'cv'},{'c':'sw','d':'fv'},{'c':'aw','d': 'gv'}]}, 
 {'a':2,'b':'b','xyz':[{'c':'ew','d':'bv'},{'c':'rw','d': 'nb'}]}, 
 {'a':3,'b':'c','xyz':[{'c':'qw','d':'fv'}]}]