Splitting multiple Dictionaries within a Pandas Column

心不动则不痛 提交于 2019-12-24 18:59:45

问题


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]

Output

"[{'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}]"

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

Appreciate any help.


回答1:


You can give this a try.

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

Your output for the row you gave is :

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



回答2:


You should try a simple method

    dt = df.topic[3]
    li = []
    for x in range(len(dt)):
       t = {dt[x]['id']:dt[x]['name']}
       li.append(t)
    print(li)

Output is-

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

First we takes the value of df.topic[3] in dt which is in form of list and dictionary inside the list, then we take an temp list li[] in which we add(append) our values, Now we run the loop for the length of values of de.topic(which we takes as dt), Now in t we are adding id or name by dt[0]['id'] or dt[0]['name'] which is '659:'Web Design' as x increase all values are comes in t, then by { : } we are converting the values in Dictionary and append it to the temporary list li



来源:https://stackoverflow.com/questions/47782052/splitting-multiple-dictionaries-within-a-pandas-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!