Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected Pandas KeyError(key) when using combination of apply lambda and if else conditon

When applying the set of apply, lambda and if-else condition, the compiler return KeyError

raise KeyError(key) KeyError: 'ss'

May I know what cause this issue

The following is referred to reproduced the above error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import pandas as pd
import numpy as np


arr=np.array([10,2,5,3,6,8,3,3,2,5,6,8,11,14,11,100,1,3,20,21])
arr=arr.reshape((1,-1))
df=pd.DataFrame(zip([4,7],[15,18],[25,40]),columns=['lb','rb','mv'])

df['ss'] = df.apply(lambda x: np.argmax(arr[0][x['lb']:x['rb']] >= 0.3 * x['mv'] ), axis=1)

df['es'] = df.apply(lambda x: np.argmax(arr[0][x['ss']:-1] < 0.3 *x['mv'] ), axis=1)

df['t']=df.apply(lambda x: 0 if x['ss']==3 else x['ss']/4)

>Solution :

I assume you forgot the axis=1 in the final lambda. It makes sense it’d evaluate as KeyError because there’s no Index value == ss. Kindly consider:

df['t']=df.apply(lambda x: 0 if x['ss']==3 else x['ss']/4,axis=1)

Rerunning on my console worked fine, hopefully it’s the same for you.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading