我有一个功能,可以通过Google DFP API将数据发送到我的广告服务器。当我的变量(order_id,targeted_placement_id等)具有硬编码的数据时,该函数有效。
我的数据来自' ad_data.csv' ,其中每列是关键,相关行中的数据是值。我想循环遍历此数据集,并将csv文件中每行的值传递到line_item
dict中的正确值。以下是我的熊猫DataFrame.head()
order_id targeted_placement_id campaign
0 3494982232 5555666677 Ad Campaign 1
1 8494984434 1112666177 Ad Campaign 2
3 4494922232 0992666677 Ad Campaign 3
4 1494984234 9494939499 Ad Campaign 4
但是,在for循环中,我想传递每一行' ad_data.csv'
from googleads import dfp
import pandas as pd
df = pd.read_csv('ad_data.csv')
order_id = df['order'].tolist()
targeted_placement_id = df['placement_id'].tolist()
campaign_name = df['campaign'].tolist()
def main(client, order_id, targeted_placement_ids, campaign_name):
line_item_service = client.GetService('LineItemService')
# Create line item objects.
line_items = []
for _ in range(1):
line_item = {
'orderId': order_id,
'name': campaign_name,
'targeting': {
'inventoryTargeting':
{'targetedPlacementIds': targeted_placement_ids},
}
}
line_items.append(line_item)
line_items = line_item_service.createLineItems(line_items)
for line_item in line_items:
print('Target id "%s", in order id "%s", named"%s" was created'
%(line_item['targetedPlacementId'], line_item['orderId'], line_item['name']))
if __name__ == '__main__':
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client, order_id, targeted_placement_id, campaign_name)
如果操作正确,line_item
应打印:
Target id 5555666677 in order id 3494982232, named Ad Campaign 1 was created
Target id 1112666177 in order id 8494984434, named Ad Campaign 2 was created
Target id 0992666677 in order id 4494922232, named Ad Campaign 3 was created
Target id 9494939499 in order id 1494984234, named Ad Campaign 4 was created
完成此任务的最佳方法是什么?
答案 0 :(得分:0)
如果你想使用 .csv 和 .json 文件,你应该使用pandas lib。
要阅读您可以使用read_csv()的文件,它会返回一个您可以操作的pandas DataFrame 对象,然后如果您想将其另存为.csv文件,请使用{ {3}}
您还可以使用iloc将系列转换为python列表 例如
DF = pandas.DataFrame.read_csv('filename.csv')
orders = DF['Orders'].tolist()
orders是一个python列表,其中包含来自.csv文件中名为Orders的列的值
修改强> 正如评论中所讨论的,您应该找出最适合您问题的工具。但是如果您计划使用大型数据集,我建议您阅读tolist()
中有关pandas内存使用情况的内容。有趣的文章:docs
编辑2:
要将 DataFrame 的每一列作为列表,您应该这样做:
orders = DF['order_id'].tolist()
targets = DF['targeted_placement_id'].tolist()
campaigns = DF['campaign'].tolist()
# print(orders, targets, campaigns)
您获得的 ValueError 是因为您尝试将这些列表作为值传递到字典的密钥orderId
,name
和{{1} }。迭代这些列表的一种方法是使用targetedPlacementIds
它将返回索引和每个位置的order_id。
e.g。
enumerate(orders)
然后要获得每个订单的0 3494982232
1 8494984434
2 4494922232
和campaigns
,您只需传递带有订单索引的列表,因此您的循环将是这样的:
targets
最后,您的# Create line item objects.
line_items = []
for index, order in enumerate(orders):
line_item = {
'orderId': order,
'name': campaigns[index],
'targeting': {
'inventoryTargeting': {
'targetedPlacementIds': targets[index]
}
}
}
line_items.append(line_item)
print(line_items)
将是一个列表,其中每个位置都是字典。
PS:
您的打印循环有错误,而不是line_items
它应该是line_item['targetedPlacementId']
您还可以检查您的DataFrame是否具有空值:
line_item['targeting']['inventoryTargeting']['targetedPlacementIds']