Ankur Anand
Ankur Anand

Reputation: 13

Convert list of dictionary in a dataframe to seperate dataframe

To convert list of dictionary already present in the dataset to a dataframe. The dataset looks something like this.

[{'id': 35, 'name': 'Comedy'}]

How do I convert this list of dictionary to dataframe?

Thank you for your time!

I want to retrieve:

Comedy

from the list of dictionary.

Upvotes: 0

Views: 50

Answers (1)

jezrael
jezrael

Reputation: 863226

Use:

df = pd.DataFrame({'col':[[{'id': 35, 'name': 'Comedy'}],[{'id': 35, 'name': 'Western'}]]})
print (df)
                               col
0   [{'id': 35, 'name': 'Comedy'}]
1  [{'id': 35, 'name': 'Western'}]

df['new'] = df['col'].apply(lambda x: x[0].get('name'))
print (df)
                               col      new
0   [{'id': 35, 'name': 'Comedy'}]   Comedy
1  [{'id': 35, 'name': 'Western'}]  Western

If possible multiple dicts in list:

df = pd.DataFrame({'col':[[{'id': 35, 'name': 'Comedy'}, {'id':4, 'name':'Horror'}],
                          [{'id': 35, 'name': 'Western'}]]})
print (df)
                                                 col
0  [{'id': 35, 'name': 'Comedy'}, {'id': 4, 'name...
1                    [{'id': 35, 'name': 'Western'}]

df['new'] = df['col'].apply(lambda x: [y.get('name') for y in x])
print (df)
                                                 col               new
0  [{'id': 35, 'name': 'Comedy'}, {'id': 4, 'name...  [Comedy, Horror]
1                    [{'id': 35, 'name': 'Western'}]         [Western]

And if want extract all values:

df1 = pd.concat([pd.DataFrame(x) for x in df['col']], ignore_index=True)
print (df1)
   id     name
0  35   Comedy
1   4   Horror
2  35  Western

Upvotes: 1

Related Questions