I have a DataFrame.
id actions
1 [{"action_type":"link_click","value":"1","1d_click":"1","7d_click":"1"},{"action_type":"page_engagement","value":"2","1d_click":"2","7d_click":"2"}]
2 [{"action_type":"link_click","value":"2","1d_click":"2","7d_click":"2"},{"action_type":"page_engagement","value":"2","1d_click":"2","7d_click":"2"}]
I have to convert like this.
id action_type value
1 link_click 1
1 page_engagement 2
2 link_click 2
2 page_engagement 2
Is this possible with pandas? If so, how can I manage to do it?
CodePudding user response:
pd.DataFrame((df := df.apply(lambda s: list(map(lambda t: [t['action_type'], t["value"]], s[1])), axis=1).explode()).to_list() , index= df.index)
if your actions
column is str
:
import ast
pd.DataFrame((df := df.apply(lambda s: list(map(lambda t: [t['action_type'], t["value"]], ast.literal_eval(s[1]))), axis=1).explode()).to_list() , index= df.index)