在 pandas 列中拆分多个词典 [英] Splitting multiple Dictionaries within a Pandas Column

查看:94
本文介绍了在 pandas 列中拆分多个词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用pandas列中的列表拆分字典,但是它对我不起作用...

I'm trying to split a dictionary with a list within a pandas column but it isn't working for me...

该列在被调用时看起来像这样;

The column looks like so when called;

df.topics[3]

输出

"[{'urlkey': 'webdesign', 'name': 'Web Design', 'id': 659}, {'urlkey': 'productdesign', 'name': 'Product Design', 'id': 2993}, {'urlkey': 'internetpro', 'name': 'Internet Professionals', 'id': 10102}, {'urlkey': 'web', 'name': 'Web Technology', 'id': 10209}, {'urlkey': 'software-product-management', 'name': 'Software Product Management', 'id': 42278}, {'urlkey': 'new-product-development-software-tech', 'name': 'New Product Development: Software & Tech', 'id': 62946}, {'urlkey': 'product-management', 'name': 'Product Management', 'id': 93740}, {'urlkey': 'internet-startups', 'name': 'Internet Startups', 'id': 128595}]"

我只希望将名称"和"id"留在topic_1,topic_2等单独的列中.

I want to only be left with the 'name' and 'id' to put into separate columns of topic_1, topic_2, and so forth.

感谢任何帮助.

推荐答案

您可以尝试一下.

import json
df.topics.apply(lambda x :  {x['id']:x['name'] for x in json.loads(x.replace("'",'"'))} )

您输入的行的输出是:

{659: 'Web Design',
 2993: 'Product Design',
 10102: 'Internet Professionals',
 10209: 'Web Technology',
 42278: 'Software Product Management',
 62946: 'New Product Development: Software & Tech',
 93740: 'Product Management',
 128595: 'Internet Startups'}

这篇关于在 pandas 列中拆分多个词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆