1

I have a function below that should return standardized outputs based on numeric ranges:

`def incident(count):
if count['incident_ct']<= 4: 
    val = 1 
elif count['incident_ct']>4 & count['incident_ct']<= 13: # 25 to 50%
    val = 2
elif count['incident_ct'] >13 & count['incident_ct']<=31: # 50 to 75%
    val = 4
elif count['incident_ct'] >31 & count['incident_ct']<=100: # 75 to 95%
    val = 8
else: 
    val = 16
return val`

Then applied to new row in the data:

`intersections['v_counts'] = intersections.apply(incident, axis = 1)`

However, the output is not giving what I specified in the ranges (only 1 or 2 in the v_count) When looking at my code, the incident_ct = 34 should be 8 and where incident_ct = 172 should be 16 enter image description here

2 Answers 2

1

Let us try use pd.cut

pd.cut(intersections['incident_ct'],bins=[4,13,31,100,..],labels=[1,2,4,8,16])

Fix your code

def incident(count):
...     if count['incident_ct']<= 4:
...         val = 1
...     elif count['incident_ct']>4 and count['incident_ct']<= 13: # 25 to 50%
...         val = 2
...     elif count['incident_ct'] >13 and count['incident_ct']<=31: # 50 to 75%
...         val = 4
...     elif count['incident_ct'] >31 and count['incident_ct']<=100: # 75 to 95%
...         val = 8
...     else:
...         val = 16
...     return val
Sign up to request clarification or add additional context in comments.

2 Comments

ok this works to an extent but there are a couple more variables where I will be using conditions from multiple columns. I'd prefer if I can get this if-else function to work properly and not use pd.cut. Do you have any torubleshooting recommendations?
that was it! I also just figured out another simple way by adding ( ) between the &.
0

Use parentheses if using the '&' def incident(count): if count['incident_ct']<= 4: # lowest percent val = 1 elif (count['incident_ct']>4) & (count['incident_ct']<= 13): # 25 to 50% val = 2 elif (count['incident_ct'] >13) & (count['incident_ct']<=31): # 50 to 75% val = 4 elif (count['incident_ct'] >31) & (count['incident_ct']<=100): # 75 to 95% val = 8 else: # upper 5% val = 16 return val

Comments

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.