首页 > 解决方案 > Pandas 按列分组并将其他列转换为键:值对

问题描述

我的原始数据格式

在此处输入图像描述

我想将其转换为:

在此处输入图像描述

标签: pythonpandasdictionary

解决方案


Try:

output = df.groupby("id").apply(lambda x: x.to_json(orient="records")[1:-1])
>>> output
id
1    {"id":1,"topic":1,"test1":"abc","test2":null,...
2    {"id":2,"topic":3,"test1":null,"test2":null,...

推荐阅读