Home > database >  How to group floats in to bins?
How to group floats in to bins?

Time:11-03

I have array (1000*1) of floats ranging from 0 to 1500.5. e.g. 100.0, 1.1, 505.3, 0.0, 210.1 and so on

I want to put them in a group with width 10 like below.

1.1   --> 10
505.3 --> 510
0.1 --> 10
210.1 --> 220

How can I do this mapping efficiently?

CodePudding user response:

A basic way is to floor divide all of numbers by 10, add 1 and multiply them by 10 again.

a = [12, 23, 34, 46, 57, 521]
print([(i // 10   1) * 10 for i in a])

as a function:

def round_up(the_list):
    return [(i // 10   1) * 10 for i in the_list]

CodePudding user response:

Look at link below. Create histogram with numpy

https://numpy.org/doc/stable/reference/generated/numpy.histogram.html

If you want visualisation look at matplotlib library

CodePudding user response:

If you are only interested in calculating the ceiled mappings, a very basic approach could be:

import math

numbers = [1.1, 505.3, 0.1, 210.1]
results = {n: math.ceil(n/10)*10 for n in numbers}

print(results)
# --> {1.1: 10, 505.3: 510, 0.1: 10, 210.1: 220}

CodePudding user response:

import numpy as np
import math
from collections import defaultdict

rand_float = np.random.uniform(low=0.1, high=35, size=(7,))

bin = defaultdict(list)

for v in rand_float:
    bin[(v // 10)*10].append(v)

print(bin)

Res:

defaultdict(<class 'list'>, {
10.0: [13.481283363231569, 17.499084832032626, 19.64083471546001], 
0.0: [7.575742141494037, 7.520094038776975, 8.05852627042683], 
20.0: [21.661914893465095]})
  • Related