python - 将 Google Ads API 结果放入 Dataframe
问题描述
我正在使用适用于 Python 的 Google Ads API SDK。我想获取一些 Ads 数据并将它们放入 Dataframe 中进行一些转换。我用下面的代码拨打了电话:
client = GoogleAdsClient.load_from_storage("config.yaml")
customer_id = '<customer_id>'
ga_service = client.get_service("GoogleAdsService")
query = """
SELECT
campaign.id,
campaign.name,
customer.id
FROM campaign
"""
response = ga_service.search_stream(customer_id=customer_id, query=query)
for batch in response:
for row in batch.results:
print(row)
df = pd.DataFrame(row)
print(df)
这是我收到的回复:
customer {
resource_name: "customers/<customer-id>"
id: <customer-id>
}
campaign {
resource_name: "customers/<customer-id>/campaigns/<campaign-id>"
name: "Test_campaign_1"
id: <campaign-id>
}
Traceback (most recent call last):
File "c:\Users\User\main.py", line 36, in <module>
print(dict(row))
TypeError: 'GoogleAdsRow' object is not iterable
我尝试使用 google.protobuf.json_format 使用以下代码将结果转换为 json/dict 格式
from google.protobuf.json_format import MessageToJson
response = ga_service.search_stream(customer_id=customer_id, query=query)
for batch in response:
for row in batch.results:
print(row)
jsonobj = MessageToJson(row)
但我收到以下错误消息:
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\proto\message.py", line 605, in __getattr__
raise AttributeError(str(ex))
AttributeError: 'DESCRIPTOR'
你能帮我解决这个问题吗?谢谢你。
解决方案
Sorry for bothering, but I found this question and got the answer for my question.
I changed my code to below (add ._pb to the response):
response = ga_service.search(customer_id=customer_id, query=query)
dictobj = MessageToDict(response._pb)
df = pd.json_normalize(dictobj,record_path=['results'])
print(df)
and it works!
推荐阅读
- javascript - 如何使用 cytoscape.js 在单个动画中沿特定方向移动所有节点?
- linkedin - 包含 timeRange 参数时,LinkedIn V2 API 错误“参数中存在未经允许的字段”
- node.js - 在nodejs中需要模块时,如何让基本目录避免使用../../../?
- c# - 当长度低于padleft的长度时,Padleft不在字符串中添加零?
- python - 在 y-achse 上找不到标签
- react-native - React Native 的“Slingshot”样式 UI 控件
- java - 编译为在 Java 6 上运行但在 Java 8 JVM 上运行的应用程序与在 Java 8 上编译的相同 App 之间的差异
- python - pip 是否将软件包安装到我的 conda 环境中?
- python - 在 SQL For 循环中迭代数组列
- java - Java:如何以用户身份执行外部命令?