Home > Net >  Create bins with 1 percentage increments?
Create bins with 1 percentage increments?

Time:08-08

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"

CodePudding user response:

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%'

  • Related