我有一个基本的python脚本,可以处理大量分析数据,但是我似乎无法获得将其泵入csv的功能,并且会搅乱错误。
AttributeError:“ dict”对象没有属性“ to_csv”
我想知道是否有人可以帮助我,这是我从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')
以下是获得输出的数据值
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
答案 0 :(得分:2)
to_csv是您要应用于字典的数据框函数,因此会出现错误。
我相信您只是犯了以下错误:
response_data.to_csv('my/file/path')
应为:
prase_response(response_data)[0].to_csv('my/file/path')
因为您的prase_response函数正在返回数据帧列表。