Oscar Silveiro
Oscar Silveiro

Reputation: 35

Splitting dictionary inside a Pandas Column into Separate Columns

I have data saved in a csv. I am querying this data using Python and turning it into a Pandas DataFrame. I have a column called team_members in my dataframe.It has a dictionaryof values. The column looks like so when called:

dt.team_members[1]

Output:

"[{'name': 'LearnFromScratch', 'tier': 'novice tier'}, {'name': 'Scratch', 'tier': 'novice tier'}]"

I tried to see this explanation and other similar:

Splitting multiple Dictionaries within a Pandas Column

But they do not work

I want to get a column called name with the names of the members of the team and another with tier of each member.

Can you help me?

Thanks!!

Upvotes: 0

Views: 168

Answers (3)

Hackaholic
Hackaholic

Reputation: 19733

You can extract name while looping over it

list(map(lambda x: x.get("name"), dt.team_members[1]))

if you need a new dataframe: then follow @vivek answer:

pd.DataFrame(dt.team_members[1])

Upvotes: 1

Vardaan Shukla
Vardaan Shukla

Reputation: 896

You can try this-

    list = dt.team_member[1]
    li = []
    for x in range(len(list)):
       t = {list[x]['name']:list[x]['tier']}
       li.append(t)
    print(li)

Output is -

    [{'LearnFromScratch': 'novice tier'}, {'Scratch': 'novice tier'}]

Upvotes: 0

Vivek Solanki
Vivek Solanki

Reputation: 462

I assume the output of dt.team_members[1] is a list.
If so, you can directly pass that list to create a dataframe something like:

pd.DataFrame(dt.team_members[1])

Upvotes: 1

Related Questions