Home > OS >  Simple built-in function to split number to bins
Simple built-in function to split number to bins

Time:11-12

Im looking for a simple functuion (maybe numpy or any other package) that will split a given number to bins, for example:

func(start=0,end=100,bins=4)

The wanted result is:

(0,25,50,75,100)

And also for a float:

For example

func(start=0,end=100,bins=6)

The wanted result is:

(0,17,34,50,67,84,100)

CodePudding user response:

Use:

import numpy as np


def fun(start=0, end=0, bins=4):
    return tuple(np.ceil(np.linspace(start=start, stop=end, num=bins   1)).astype(np.int32))


print(fun(start=0, end=100, bins=4))
print(fun(start=0, end=100, bins=6))

Output

(0, 25, 50, 75, 100)
(0, 17, 34, 50, 67, 84, 100)

CodePudding user response:

To do this without numpy, you can figure out the gap with by dividing (ends - start) / bins, then use a range over the number of bins ( 1) and round accordingly.

import math

def f(start, end, bins):
    gap = (end - start) / bins
    return tuple(math.ceil(n * gap   start) for n in range(bins   1))
    
f(start=0,end=100,bins=4)
# (0, 25, 50, 75, 100)

f(start=0,end=100,bins=6)
# (0, 17, 34, 50, 67, 84, 100)

f(start=10,end=50,bins=6)
# (10, 17, 24, 30, 37, 44, 50)
  • Related