Create bins with 1 percentage increments?

Question:

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"
Asked By: titutubs

||

Answers:

This will allow you to choose the increments that you want to look at. First, find the remainder of your value * 100 divided by the increment, then multiply that number by the increment to get the bottom range of your increments. If the bottom range is less than 100, print the bottom range to the bottom range plus your increment. Account for if the bottom range is 100 (because you don’t want to put that in e.g. 100-107%), then return an "Error" message if the value would be placed in a range above 100%.

def conditions(value, increment):
    bottomRange = value*100 // increment * increment
    if value > 1:
        return("Error")    
    elif (bottomRange + increment) <= 100:
        return f"{bottomRange} - {bottomRange+increment}%"
    elif (bottomRange + increment) > 100 or value == 1:
        return f"{bottomRange} - 100%"      

conditions(0.62, 10) # output: '60.0 - 70.0%'

conditions(0.05, 3) # output: '3.0 - 6.0%'

conditions(0.98, 7) # output: '98.0 - 100%'
Answered By: Michael S.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.