Hello Stackoverflowers!
I have a DataFrame
, obtained from Facebook Marketing API
, and I’d like to unnest
a column into several rows.
This is the a sample of the data I obtained through the API:
ad_name video_play_curve_actions
ad_1 [{'action_type': 'video_view', 'value': [100, 40, 16, 10, 7, 5, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}]
ad_2 [{'action_type': 'video_view', 'value': [100, 51, 22, 13, 9, 7, 6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}]
What I am looking for, is an outcome that looks like illustrated below
I’d need a for loop for this because the solution needs to work for many 100 rows.
I’ve added example data and desired output to this sheet: https://docs.google.com/spreadsheets/d/1jjbtJlfBNZV_wyyAoPY_scyn_jCNFD04XO1-JsztKAg/edit?usp=sharing
Really hope someone here can help me out.
Thanks in advance
Edit:
Thank you so much. Seems like there are multiple ways to fix it, but all the solutions included: pandas.explode
: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html
Will definitely use it going forward.
Happy Wednesday
3
Answers
You’re looking for
pandas.explode
: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html, plus some necessary preprocessing for yourvideo_play_curve_actions
column.output:
Note that I used
eval
here to process the values invideo_play_curve_actions
which isn’t always considered best practice. If the input contained double quotes"
instead of single quotes'
we could have usedjson.loads
instead.One way would be to grab the values of your video_play_curve_actions using
str.split()
, and thenexplode()
:prints:
Use
ast.literal_eval
to convert the strings to a python data structure (list of dict here) then explode and extract ‘value’ key:Output:
Note: The best way is probably to use directly the response from Facebook Marketing API rather than load data from an excel file.