Home > database >  Applying a function on each row of dataframe and ignoring the exception (if any)
Applying a function on each row of dataframe and ignoring the exception (if any)

Time:10-07

Am trying to run an apply lambda function on each row of a dataframe. However, the function can return certain exceptions/errors. How can i bypass/ignore those exceptions, and continue execution? I tried using an if else within the apply function but it did not go well.

Here is my piece of code:

df['IV'] = df.apply(lambda row: iv(row['Close_x'], row['Close_y'], row['Strike'], row['TTE_x'], 0, flag='c')) 

CodePudding user response:

I haven't seen an elegant way of suppressing exceptions in a lambda, though it is very rare that you'd really need to. As mentioned in thefourtheye's comment, you can do this though

def myfunc(row):
    try:
        iv(row['Close_x'], row['Close_y'], row['Strike'], row['TTE_x'], 0, flag='c')
    except ExceptionThatIVSometimesThrows as e:
        print("Error on row", row.name)

df['IV'] = df.apply(myfunc)

CodePudding user response:

for i in range(len(df.index)-1):
    try:
        df[i] = df[i].apply(lambda row: iv(row['Close_x'], row['Close_y'], row['Strike'], row['TTE_x'], 0, flag='c')) 
    except:
        ...
  • Related