I have a column in my dataframe with list of dict inside.
Here is the first element of the 'reviews' column:
I would like to extract 'item_id' et 'recommend' key to put them in new column of the previous dataframe like this:
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)
key = 'Fruits'
df[key] = df['B'].apply(lambda ls: [d[key] for d in ls])
print(df)