python聚合并使用DataFrame创建字典

迪帕战士

我开始学习熊猫,并陷入以下问题:
我的示例数据框如下

id      batchid     batchname
1       101         accounts
2       101         accounts
1       102         finance
2       104         admin

我需要创建一个聚合的新数据框,batchidbatchname基于id如下所示:

id      group_info
1       [{batchid:101, batchname:accounts},{batchid:102, batchname:finance}]
2       [{batchid:101, batchname:accounts},{batchid:104, batchname:admin}]

我尝试使用DataFrame.apply()哪个消耗DataFrame.stack()但给出错误。
有什么建议吗?

BEN_YO

groupby + to_dict

df.groupby('id')['batchid','batchname'].apply(lambda x : x.to_dict('r')).to_frame('group_info').reset_index()
Out[84]: 
   id                                         group_info
0   1  [{'batchname': 'accounts', 'batchid': 101}, {'...
1   2  [{'batchname': 'accounts', 'batchid': 101}, {'...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章