如何在for循环中处理pandas KeyError



我在for循环中编写了以下代码来处理我遇到的pandas KeyError,但我似乎无法在这个块中使用continue语句和except关键字。我该怎么修?

最初,我想引发一个异常来显示那些不在表中的键,并在遇到这些KeyErrors时让for循环继续。


for i in range(1000):
# do something 
try:
u= str(df.loc[item_a, 'E'])
v= str(df.loc[item_a, 'D'])
w= str(df.loc[item_b, 'E'])
x= str(df.loc[item_b, 'D'])
continue
except KeyError:
raise Exception('KeyError: {} do not exist in the table.'.format(a))

# do something else

如果引发错误,执行将停止。您可以将continue语句放在except块中。这将允许您继续进行循环。只需确保在点击continue语句之前打印出/注销您需要的任何信息。

for i in range(1000):
# do something 
try:
u= str(df.loc[item_a, 'E'])
v= str(df.loc[item_a, 'D'])
w= str(df.loc[item_b, 'E'])
x= str(df.loc[item_b, 'D'])
except KeyError:
print('KeyError: {} does not exist in the table.'.format(your_variable))
continue

最新更新