gpt4 book ai didi

python - 使用groupby将数据框转换为字典

转载 作者:太空宇宙 更新时间:2023-11-04 11:21:35 25 4
gpt4 key购买 nike

我有一个数据框

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'}]}

最佳答案

我想你需要DataFrame.to_dict使用记录:

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'}]}]

关于python - 使用groupby将数据框转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55861743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com