Reputation: 168
I am using multiple try/except blocks to assign values of a dataframe (say data) to 3 variables(say b,c,d) I want to handle IndexErrors if positional indexer is out-of-bounds. What I am currently doing is shown below:
b,c,d=None,None,None
try:
b=data.iloc[1,1]
except:
pass
try:
c=data.iloc[2,1]
except:
pass
try:
d=data.iloc[0,2]
except:
pass
I want to know if there is a better of doing this like a function try_except() or something so that I can use it as shown below:
try_except(b=data.iloc[1,1])
try_except(c=data.iloc[2,1])
try_except(d=data.iloc[0,2])
Upvotes: 0
Views: 1627
Reputation: 59092
You could just write a function that performs a lookup and catches the exception, but incidentally, except: pass
is probably a bad idea. You should be more specific with your error handling.
def safe_get(container, i, j):
try:
return container[i,j]
except IndexError: # or whatever specific error you're dealing with
return None
b = safe_get(data.iloc, 1, 1)
c = safe_get(data.iloc, 2, 1)
d = safe_get(data.iloc, 0, 2)
Upvotes: 2