1

I want to apply a function that creates a column based on variables in 2 other columns.

  1. One column 'SSPstaterank' returns the suburb ranking.

  2. The second column 'SSPstaterank%' returns the suburb ranking percentile.

I thought this code would work, but it returns:

TypeError: ("'DataFrame' object is not callable", 'occurred at index 0')

def func1 (a,b):
    if a == 1:
        return 'the #1 suburb'
    elif b >= 0.95:
        return 'ranked top 5% of suburbs'
    elif b >= 0.9:
        return 'ranked top 10% of suburbs'
    else:
        return 'none'

df2['rankdescript'] = df2.apply(lambda x: df2(x['SSPstaterank'], x['SSPstaterank%']), axis=1)

1 Answer 1

4

Use func1 instead df2:

df2['rankdescript'] = df2.apply(lambda x: func1(x['SSPstaterank'],x['SSPstaterank%']), axis=1)

Another solution with numpy.select should be faster:

df2 = pd.DataFrame({'SSPstaterank':[2,1,2,2,7],
                    'SSPstaterank%':[.99,.93,.93,.98,.23]})


m1 = df2['SSPstaterank'] == 1
m2 = df2['SSPstaterank%'] >= 0.95
m3 = df2['SSPstaterank%'] >= 0.9

masks = [m1, m2, m3]
vals = ['the #1 suburb','ranked top 5% of suburbs','ranked top 10% of suburbs']

df2['rankdescript'] = np.select(masks, vals, default='not matched')
print (df2)
   SSPstaterank  SSPstaterank%               rankdescript
0             2           0.99   ranked top 5% of suburbs
1             1           0.93              the #1 suburb
2             2           0.93  ranked top 10% of suburbs
3             2           0.98   ranked top 5% of suburbs
4             7           0.23                not matched
Sign up to request clarification or add additional context in comments.

1 Comment

The second solution is probably faster; using df.apply(...,axis=1) is usually quite slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.