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’
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)
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’
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)