Python- 'ValueError: invalid literal for int() with base 10' When Converting a List with Strings to Integers

Python- 'ValueError: invalid literal for int() with base 10' When Converting a List with Strings to Integers

我正在使用 Pandas read_excel 函数为我的工作簿中的每一列创建 data_frames。数据在我们的广告服务器中与 Google DFP API to create Line Items 一起使用。

我正在循环并将数据从我的 data_frames 传递到字典中作为值。下面是我的代码:

import pandas as pd
from googleads import dfp

workbook = 'dfp-migration-data.xlsx'
sheet = 'main'

df = pd.read_excel(workbook, sheet_name=sheet)

campaign_id = df['order_id'].tolist()
campaign = df['order'].tolist()
target = df['placement_id']

placement_id = []

def create_line_item(client, orders):
     line_item_service = client.GetService('LineItemService')

line_items = []
for index, order in enumerate(orders):

    line_item = {
        'name': line_item_name[index],
        'orderId': int(campaign_id[index]),
        'targeting': {
            'inventoryTargeting': {
                'targetedPlacementIds': placement_id[index]},
             },

    line_items.append(line_item)

# Add line items to DFP
line_items = line_item_service.createLineItems(line_items)

# Display results
for line_item in line_items:
    print(f"Order ID: {line_item['orderId']}"
          f"Line Item: {line_item['name']}"
          f"Placement IDs: {line_item['targeting']['inventoryTargeting']['targetedPlacementIds']}\n"

if __name__ == '__main__':
    dfp_client = dfp.DfpClient.LoadFromStorage()
    create_line_item(dfp_client, campaign)

我遇到的问题是 target 数据框,它在每个单元格中有多个值。例如

df['placement_id'].head()
0    28816768, 28809669, 28809672, 28809675, 288092...
1    28825664, 28825670, 28825511, 28825673, 288256...
2    28825538, 28816006, 28814215, 28825544, 288254...
Name: placement_id, dtype: object

placement_id 传递到 targetedPlacementIds 键时,我收到一个错误,这是有道理的,因为我的数据框中的数据是一个字符串。但是,如果我尝试用 int() 函数包装 'placement_id',我会收到 'ValueError: invalid literal for int() with base 10' 错误。我曾尝试在 Pandas 中使用 to_numbers() 和 astype(int()) 函数,但收到相同的错误。

如何将 placement_ids 从字符串转换为整数,以便能够将数据传递到我的 line_item 字典中?

如果您允许每一行都有一个 int 值的列表,则下面应该有效。

df['placement_id'] = df['placement_id'].apply(lambda x: x.split(", "))
df['placement_id'] = df['placement_id'].apply(lambda x: [int(y) for y in x])

你会得到这个:

In [3]: df['placement_id'].head()
Out[3]:
0    [28816768, 28809669, 28809672, 28809675, 288092]
1    [28825664, 28825670, 28825511, 28825673, 288256]
2    [28825538, 28816006, 28814215, 28825544, 288254]
Name: placement_id, dtype: object

In [4]: type(df['placement_id'][0][0])
Out[4]: int