Error handling with Lambda function applied to a DF

Question:

Doing the following :

self.FUTcurve['Maturity'] = self.FUTcurve.apply(
            lambda x: blp.bdp(x.security_description,"X")["X"][0], axis=1)

does not work since sometimes

blp.bdp(x.security_description,"X") 

returns an empty array.

I know how to handle error but nut in lamnda func ..
The error raised is :

KeyError: ‘X’

Asked By: TourEiffel

||

Answers:

Can you try the following:

self.FUTcurve['Maturity'] = self.FUTcurve.apply(
            lambda x: 'empty array' if 'X' not in blp.bdp(x.security_description,"X") else blp.bdp(x.security_description,"X")["X"][0], axis=1)

Cleaner solution:

def my_func(x):
    arr = blp.bdp(x.security_description, "X")
    if 'X' in arr:
        return arr['X'][0]
    else:
        return 'empty array'   
self.FUTcurve['Maturity'] = self.FUTcurve.apply(lambda x: my_func(x))

Directly calling the security_description column:

def my_func(x):
    arr = blp.bdp(x, "X")
    if 'X' in arr:
        return arr['X'][0]
    else:
        return 'empty array'   
self.FUTcurve['Maturity'] = self.FUTcurve['security_description'].apply(my_func)
Answered By: Jeril
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.