4

I'm trying to get the results of a Facebook ads insights query into a pandas dataframe but the returned object is not cooperating.

I'm running a basic async usage example as is outlined by Facebook here: https://developers.facebook.com/docs/marketing-api/insights/v2.6

campaign = Campaign(my_campaign)
params = {
    'level': 'ad',
    'date_preset': 'lifetime',
    'time_increment': 1,
    'fields': ['date_start', 'ad_id', 'ad_name', 'spend', 'reach',  'total_actions']
}
async_job = campaign.get_insights(params=params, async=True)

async_job.remote_read()

while async_job[AsyncJob.Field.async_percent_completion] < 100:
    time.sleep(1)
    async_job.remote_read()

time.sleep(1)

result = async_job.get_result()

And then I'm trying to change the result into a list a la this response here: https://stackoverflow.com/a/36397567/5459606

result = [x for x in async_job.get_result()]
type(result)

This returns the result as a list, however I'm getting an error when I try to read this into pandas using df = pd.DataFrame(result)

if I look at what is being returned I see each list entry looks like this:

<AdsInsights> {
    "ad_id": "6035212284443",
    "ad_name": "Outlook - Image 2, copy 1",
    "date_start": "2015-11-21",
    "date_stop": "2015-11-21",
    "reach": 625,
    "spend": 2.4,
    "total_actions": 10
}

And if I ask for the type of this obejct, it's a facebookads.adobjects.adsinsights.AdsInsights and not a dictionary which I am guessing is the problem. Does anyone know how to solve this and let me use pandas to read these Facebook results.

Community
  • 1
  • 1
Sam Taylor
  • 41
  • 1
  • 5

1 Answers1

1

HaHa,you can use list(),and then use pandas.DataFrame. You can look here [How to parse nested FB API response from Python SDK

Community
  • 1
  • 1
ye jiawei
  • 882
  • 7
  • 7
  • 1
    Hey, thanks for the reply. I followed the way you did it in your example (result = [x for x in async_job.get_result()]) but I was thrown an error. KeyError: 'None' – Sam Taylor Apr 22 '16 at 18:21
  • 1
    oh,i forget you use the "async". If you want to get the data you should change "async=True" to "async=False". I help this time it can help. – ye jiawei Apr 23 '16 at 14:36
  • Hey I really appreciate the help. Unfortunately it's still not working due to a KeyError: 'None'. I think the problem is that when I look at the a single entry in the results list using result[0].keys() I can see a ton of keys in there (regardless of the ones I choose in my fields parameter) and one of then is None, not as a string. Just sitting there as None, right in the middle, messing things up (I think). – Sam Taylor Apr 25 '16 at 15:39