0

I have a basic python script that churns out a load of analytics data but I can't seem to get it to pump it out into a csv and it's churning back the error.

AttributeError: 'dict' object has no attribute 'to_csv'

I was wondering if someone could help me, here is my code which I got from https://medium.com/analytics-for-humans/submitting-your-first-google-analytics-reporting-api-request-cdda19969940

api_name = 'analyticsreporting'
api_version = 'v4'


api_client = google_build(serviceName=api_name, version=api_version, http=authorized)
sample_request = {
      'viewId': '151121821',
      'dateRanges': {
          'startDate': datetime.strftime(datetime.now() - timedelta(days = 30),'%Y-%m-%d'),
          'endDate': datetime.strftime(datetime.now(),'%Y-%m-%d')
      },
      'dimensions': [{'name': 'ga:date'}],
      'metrics': [{'expression': 'ga:sessions'}]
    }

response = api_client.reports().batchGet(
      body={
        'reportRequests': sample_request
      }).execute()
print(response)

def prase_response(report):

    """Parses and prints the Analytics Reporting API V4 response"""

    result_list = []


    data_csv = []
    data_csv2 = []


    header_row = []


    columnHeader = report.get('columnHeader', {})
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
    dimensionHeaders = columnHeader.get('dimensions', [])


    for dheader in dimensionHeaders:
        header_row.append(dheader)
    for mheader in metricHeaders:
        header_row.append(mheader['name'])


    rows = report.get('data', {}).get('rows', [])
    for row in rows:
        row_temp = []
        dimensions = row.get('dimensions', [])
        metrics = row.get('metrics', [])
        for d in dimensions:
            row_temp.append(d)
        for m in metrics[0]['values']:
            row_temp.append(m)
            data_csv.append(row_temp)


        if len(metrics) == 2:
            row_temp2 = []
            for d in dimensions:
                row_temp2.append(d)
            for m in metrics[1]['values']:
                row_temp2.append(m)
            data_csv2.append(row_temp2)


    result_df = pandas.DataFrame(data_csv, columns=header_row)
    result_list.append(result_df)
    if data_csv2 != []:
        result_list.append(pandas.DataFrame(data_csv2, columns=header_row))

    return result_list

response_data = response.get('reports', [])[0]
print(prase_response(response_data)[0])

response_data.to_csv('my/file/path')

Here are the data values that get output

ga:date ga:sessions

0   20180626          94
1   20180627          78
2   20180628          33
3   20180629          78
4   20180702          79
5   20180703          90
6   20180704          78
7   20180705          66
8   20180706          60
9   20180708           1
10  20180709         101
11  20180710          80
12  20180711          69
13  20180712          82
14  20180713          76
15  20180714           1
16  20180716          91
17  20180717          84
18  20180718          79
19  20180719          58
20  20180720          67
21  20180722           1
22  20180723          95
23  20180724          92
24  20180725          85
25  20180726          76
Yarry T
  • 151
  • 3
  • 15
  • 2
    `response_data = response.get('reports', [])[0] ` This is probably not a dataframe, but a dict. Thus the error "dict" object has no attribute to_csv. – user2906838 Jul 26 '18 at 16:11
  • I'm guessing this is not a simple fix, I am just learning this whole api and python so I followed the tutorial which I mentioned in the description. I'm surprised that everything works in the code apart from the last part. Would there be any easy way to convert this to a dataframe and then export it to csv – Yarry T Jul 26 '18 at 16:13
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Jul 26 '18 at 16:14
  • In this case, I expect that reducing this to a MCVE will expose your error without a need to post: checking your data types and isolating the problem code will show just where you changed from `data frame` to `dict` in your data handling. – Prune Jul 26 '18 at 16:16
  • Can you please add the response_data values? if it's a collection of dict, you could create a dataframe out of it, and then to_csv would work fine. – user2906838 Jul 26 '18 at 16:16
  • Possible duplicate of [AttributeError: 'dict' object has no attribute](https://stackoverflow.com/questions/35407560/attributeerror-dict-object-has-no-attribute) – Linda Lawton - DaImTo Jul 27 '18 at 15:14

1 Answers1

2

to_csv is a dataframe function which you are trying to apply to a dict, hence the error.

I believe you simply made the following mistake:

response_data.to_csv('my/file/path')

should be:

prase_response(response_data)[0].to_csv('my/file/path')

Because your prase_response function is returning a list of dataframes.