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

Time:02-25

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

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)

CodePudding user response:

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.

  • Related