Issue
I have a dataframe with column activity_percentage of a customer. This range is from 0-100%. Now, I want to create bin for each percentage but my current approach will require me to manually create 100 bins which is probably not the best way. How can I achieve this in a more programmatic way?
def conditions(x):
if x >=0 and x<=0.01: return "0-1%"
elif x >0.01 and x<=0.02: return "1-2%"
elif x >0.02 and x<=0.03: return "2-3%"
.... return 99-100%
else:
return "error"
Solution
Put it in a for loop:
def conditions(x):
for y in range(0, 101):
if y >= x*100:
return f"{y} - {y+1}%"
return "Error"
conditions(0.05)
Output:
'5 - 6%'
To do 5% increments:
def conditions(x):
for y in range(0,101, 5):
if y > x*100:
return f"{y-5} - {y}%"
return "Error"
conditions(0.68)
Output: '65 - 70%'
Answered By - Michael S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.