Skip to content Skip to sidebar Skip to footer

Splitting Multiple Dictionaries Within A Pandas Column

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': 'webdesig

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

Solution 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

Post a Comment for "Splitting Multiple Dictionaries Within A Pandas Column"