Python – When apply a function to a list, it occurs “TypeError: ‘Int64Index’ object is not callable”

pandaspython

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] equals 1, and ls.index(1) is invalid expression. This is so as ls is Series object and Series.index is not callable, as contrary to list.index in your working case.

To be applicable in case of DataFrame, modify your function to

def titleNot0(ls):
    try:
        return filter(lambda x:x!=0,ls)[0]
    except IndexError: 
        return 2

and invoke as

>>> df = pd.DataFrame([[1,1,1,2,3],[0,1,2,0,1]]).T
>>> df.columns = list('AB')
>>> df.groupby('A')['B'].agg(titleNot0)
A
1    1
2    2
3    1
Name: B, dtype: int64
Related Topic