问题描述
我正在尝试使用python的pandas库创建一个数据框,并利用从请求响应获得的数据。问题是当API上没有该项目可用时,它将引发KeyError并使程序崩溃。
正在对每个产品名称的源数据帧进行迭代。然后,它将获取该行的产品名称,并找到存在多少个不同的SKU,在每个SKU的新数据框中创建一行,并向新数据框中添加一些数量和其他所需信息。想法是在第一个数据帧上重复所有相同信息的行,但是其中的许多SKU都会用该SKU的数量和包装ID进行更新。
如果返回的响应的长度为0,我仍然希望它在第一个数据帧后追加行
XAML
除少数项目外,其他各项均适用。这是我得到的错误。
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
这已占用了我整个周末和整个睡眠时间,应在美国标准时间周一上午10点(仅在两天内通知)。请帮助我。
解决方法
捕获错误并继续进行应该可以。类似于:
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
....