I want to group by "objid", and get the first NONE-ZERO level within the same id. if within the same list, all level is 0, I will make it return 2. What I do is:
objid level color
1 0 red
1 1 blue
1 2 yellow
2 0 white
3 1 red
Result:
objid level
1 1
2 2
3 1
def titleNot0(ls):
try:
Not0= ls.index(filter(lambda x:x!=0,ls)[0])
return ls[Not0]
except IndexError:
return 2
userTitle = JobData.groupby("candidate_id")["TitleLevel"].apply(titleNot0)
I have tried on some simple list like: x=[0,1,2], titleNot0(x)
. It works. But if I apply the function to the groupby, it returns "TypeError". Please help me to fix it. Thank you!
Best Answer
Error lies in line
ls.index(filter(lambda x:x!=0,ls)[0])
.Result of
filter(lambda x:x!=0,ls)[0]
equals1
, andls.index(1)
is invalid expression. This is so as ls isSeries
object andSeries.index
is not callable, as contrary tolist.index
in your working case.To be applicable in case of DataFrame, modify your function to
and invoke as