gpt4 book ai didi

python - AttributeError:“dict”对象没有属性“to_csv” Google Analytics API报告V4

转载 作者:行者123 更新时间:2023-12-03 17:14:46 27 4
gpt4 key购买 nike

我有一个基本的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

最佳答案

to_csv是您要应用于字典的数据框函数,因此会出现错误。

我相信您只是犯了以下错误:

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


应该:

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


因为您的prase_response函数正在返回数据帧列表。

关于python - AttributeError:“dict”对象没有属性“to_csv” Google Analytics API报告V4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51543218/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com