4
votes

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.

2

2 Answers

1
votes

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

0
votes

You can do this using windsor.ai as well. You just have to connect your facebook account to windsor.ai, and then use their Python SDK (pywindsorai) to load in the data into pandas.

import pandas as pd
 
from pywindsorai.client import Client
 
api_key = 'xxx'  # Get this from your windsor.ai account
 
client = Client(api_key)
campaign_clicks = client.connectors(date_preset='last_7d', fields=['date','clicks','spend'])

df = pd.DataFrame(campaign_clicks['data'])

Check this blog post to learn more: https://www.windsor.ai/multichannel-marketing-data-analysis-via-python-using-pywindsorai/