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
:
def find_action (list_action, action_type, what):
for action in list_action:
# for each action, see if the key action_type is the one wanted and what in the keys
if action['action_type'] == action_type and what in action.keys():
return action[what]
# if not the right action type found, then empty
return ''
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"