我正在尝试将 Google Analytics Admin API 响应获取到 Pandas 数据框中,但在解析结果时遇到问题。我正在使用 admin_v1beta 库中的 list customDimensions 方法。我可以看到结果,但我还没有弄清楚如何将它们转换为可在 Pandas 中使用的格式。
我的功能:
def get_custom_dimensions(property_filter):
client = admin_v1beta.AnalyticsAdminServiceClient()
request = admin_v1beta.ListCustomDimensionsRequest(
parent=property_filter
)
return client.list_custom_dimensions(request=request)
输出:
ga4_custom_dimensions = get_custom_dimensions("properties/xxx")
print(type(ga4_custom_dimensions))
<class 'google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomDimensionsPager'>
print(ga4_custom_dimensions)
ListCustomDimensionsPager<custom_dimensions {
name: "properties/xxx/customDimensions/yy1"
parameter_name: "custom_dimension_zz1"
display_name: "Custom Dimension ZZ1"
description: "The dimension ZZ1 useful for filtering."
scope: EVENT
}
custom_dimensions {
name: "properties/xxx/customDimensions/yy2"
parameter_name: "custom_dim...
响应有它自己的类,所以在我可以用它做任何事情之前,我需要转换它,但我还没有弄清楚如何转换。我的第一个想法是转换为 JSON:
custom_dimensions_json_1 = json.dumps(ga4_custom_dimensions.__dict__)
custom_dimensions_json_2 = json.dumps(vars(ga4_custom_dimensions))
这些会产生相同的错误,
TypeError: Object of type _GapicCallable is not JSON serializable
.
我的下一次尝试是通过 Pandas
json_normalize
方法:
custom_dimension_df = pd.json_normalize(ga4_custom_dimensions)
结果是一个只有索引的数据帧。
最后,我尝试直接解析结果:
temp_df = pd.DataFrame(ga4_custom_dimensions['custom_dimensions'])[['name',
'parameter_name',
'display_name',
'description',
'scope']]
这会产生“TypeError:
ListCustomDimensionsPager' object is not subscriptable
.
任何人都可以指导我如何解析 Pandas 中的 API 响应吗?
我能够解决这个问题并继续前进。我更新了我的函数以迭代一系列
str.replace()
步骤以使响应有效 json,然后从那里创建 pandas 数据帧。
def get_custom_dimensions(property_filter):
client = admin_v1beta.AnalyticsAdminServiceClient()
request = admin_v1beta.ListCustomDimensionsRequest(
parent=property_filter
)
full_response = client.list_custom_dimensions(request=request)
df_list = []
for response in full_response:
step1 = response.__dict__
step2 = str(step1)
step3 = step2.replace(': name:', ': "name" :')
step4 = step3.replace('parameter_name:', ', "parameter_name" :')
step5 = step4.replace('display_name:', ', "display_name" :')
step6 = step5.replace('description:', ', "description" :')
step7 = step6.replace('scope:', ', "scope" :')
step8 = step7.replace('disallow_ads_personalization: true', ', "disallow_ads_personalization" : "true"')
step9 = step8.replace("'_pb': ", "")
step10 = step9.replace(' : EVENT', ' : "EVENT"')
step11 = step10.replace(' : USER', ' : "USER"')
step12 = step11.encode('utf-8').decode('unicode_escape')
step13 = json.loads(step12)
df_list.append(step13)
return pd.DataFrame(df_list)
调用此函数会生成一个带有响应的 Pandas 数据帧,然后可以保存、操作等。
custom_dimension_df = get_custom_dimensions("xxx")
我没有太多在 python 中使用类对象的经验,我的解决方案不是很优雅,但它有效。