【问题标题】:How to ignore a key error and continue the while loop如何忽略关键错误并继续 while 循环
【发布时间】:2020-09-28 09:53:07
【问题描述】:

我正在尝试使用通过请求响应获得的数据使用 python 的 pandas 库创建一个数据框。问题是当 API 上没有可用的项目时,它会引发 KeyError 并使程序崩溃。

源数据框正在遍历每个产品名称。然后,它获取该行的产品名称并查找存在多少不同的 SKU,在新数据框中为每个 SKU 创建一行,并将一些数量和其他所需信息添加到新数据框中。我们的想法是在第一个数据帧上重复一行,其中包含所有相同的信息,但是那里的许多 SKU 都使用该 SKU 的数量和包裹 ID 进行了更新。

如果返回的响应长度为0,我仍然希望它从第一个数据帧中追加行

def create_additional_rows_needed(comb_data):
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("test")

new_combined_data = pd.DataFrame(columns=comb_data.columns)

COVA_DATA_LEN = 2993

row = 0
current_item = ''
   
while row < len(comb_data):
    number_of_skus = 0
    current_item = comb_data.iloc[row, 1]
    if (len(current_item)) is not None:
        number_of_skus = len(find_gb_product(current_item))
    else:
        number_of_skus = 0
    current_quantity = find_gb_product(current_item).iloc[number_of_skus - 1, find_gb_product(current_item).columns.get_loc('quantity')]
    logger.info('Current Quantity: {}'.format(current_quantity))
    current_package = find_gb_product(current_item)['lot_number'][number_of_skus - 1]

    if number_of_skus == 0:
        pass

    while number_of_skus > 0:
        

        logger.info('Current Item: {}'.format(current_item))
        logger.info('Number of Skus: {}'.format(number_of_skus))
        logger.info('Appending: {}'.format(comb_data.iloc[row, 1]))
        

        new_combined_data = new_combined_data.append([comb_data.iloc[row, :]])
        new_combined_data.iloc[-1, new_combined_data.columns.get_loc('TotalOnHand')] = current_quantity
        new_combined_data.iloc[-1, new_combined_data.columns.get_loc('PackageId')] = current_package
                
        number_of_skus = number_of_skus - 1

    logger.info('Finished index {}'.format(row))
    row = row + 1
    logger.info('Moving to index {}'.format(row))

return new_combined_data

除了少数之外,它适用于所有项目。这是我得到的错误。

KeyError  
   2889                 return self._engine.get_loc(casted_key)
   2890             except KeyError as err:
-> 2891                 raise KeyError(key) from err
   2892 
   2893         if tolerance is not None:

KeyError: 'quantity'

这已经占用了我整个周末和所有的睡眠时间,并于周一上午 10 点 MST 到期,只有两天通知。请帮帮我。

【问题讨论】:

标签: python-3.x pandas keyerror


【解决方案1】:

捕获错误并继续应该可以工作。大致如下:

while row < len(comb_data):
    ....
    try:
        current_quantity = find_gb_product(current_item).iloc[number_of_skus - 1, find_gb_product(current_item).columns.get_loc('quantity')]
    except KeyError:
        continue
    ....
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2022-01-26
    • 2015-05-12
    • 2013-03-13
    相关资源
    最近更新 更多