Skip to content Skip to sidebar Skip to footer

Convert List Of Dictionaries Containing Another List Of Dictionaries With Multiple Values To Dataframe

This question is in addition to the question posted at Convert list of dictionaries containing another list of dictionaries to dataframe I was asked to add a Parameter in my API c

Solution 1:

I think by changing my answer to your previous question, you can achieve what you want. Still start by filling nan with empty list:

df['actions'][df['actions'].isnull()] = df['actions'][df['actions'].isnull()].apply(lambda x: [])

Then define the function find_action with another parameter what:

deffind_action(list_action, action_type, what):
    for action inlist_action:# for each action, see if the key action_type is the one wanted and what in the keysif action['action_type'] == action_type and what in action.keys():
            return action[what]
    # if not the right action type found, then emptyreturn''

Now, you can use apply with two arguments:

df['a2cart_view'] = df['actions'].apply(find_action, args=(['add_to_cart','view']))
df['a2cart_click'] = df['actions'].apply(find_action, args=(['add_to_cart','click']))
df['pur_view'] = df['actions'].apply(find_action, args=(['purchase','view']))
df['pur_click'] = df['actions'].apply(find_action, args=(['purchase','click']))

and drop the column actions:

df = df.drop('actions',axis=1)

Post a Comment for "Convert List Of Dictionaries Containing Another List Of Dictionaries With Multiple Values To Dataframe"