Home > database >  Transform a list of dict from a column in a column of list
Transform a list of dict from a column in a column of list

Time:01-19

I have a column in my dataframe with list of dict inside.

enter image description here

Here is the first element of the 'reviews' column:

enter image description here

I would like to extract 'item_id' et 'recommend' key to put them in new column of the previous dataframe like this:

enter image description here

CodePudding user response:

Assuming you are trying this on Pandas dataframe, you can use custom function or a lambda function to extract key values from a list of dicts

import pandas as pd

df = pd.DataFrame({'A': 'x',
                    'B': [[{'Fruits': 'Apple', 'Vegetables': 'Tomato'},
                         {  'Fruits': 'Orange', 'Vegetables': 'Onion'},
                         {'Fruits': 'Mango', 'Vegetables': 'Potato'}]]})

print(df)

enter image description here

key = 'Fruits'
df[key] = df['B'].apply(lambda ls: [d[key] for d in ls])

print(df)

enter image description here

  • Related