Lee
Lee

Reputation: 35

How to handle pandas KeyError in a for loop?

I wrote the following code in a for loop to handle the pandas KeyError I met, but it seemed that I couldn't use a continue statement and except keyword in this block. How could I fix it?

Originally, I would like to raise an exception to show those keys that are not in the table and let the for loop continue while meeting with those KeyErrors.


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

Upvotes: 1

Views: 2209

Answers (1)

distro
distro

Reputation: 712

If you raise an error, execution will stop. You can put your continue statement in the except block. That will allow you to continue going through the loop. Just make sure to print out/log out whatever information you need before hitting the continue statement.

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

Upvotes: 1

Related Questions