to clustter the floating point data into suitable buckets in python
Question: I have a csv file which has thousands of floating point values arranged in
ascending order. I want to bunch/cluster those values into suitable clusters.

    
    
    for example :
    0.001
    0.002
    0.013
    0.1
    0.101
    0.12
    0.123
    0.112
    0.113
    0.2
    

so the clusters should be like

    
    
    0 - 0.1 with count 4
    0.1 - 0.2 with count 6
    

How can I do this clustering task automatically in python ? Do I need to keep
some initial parameters? I have no clue in this regard. Please help.


Answer: You can `bisect.bisect_left` to find where the element would land in a list of
keys with the correct increment, then simply use that index to get the element
from the list of keys and increment its count using a dict.

    
    
    from bisect import bisect_left
    with open("test.txt") as f:
        keys = [0.1, 0.2]
        d = dict.fromkeys(keys, 0)
        for line in f:
            ind = bisect_left(keys, float(line))
            d[keys[ind]] += 1
    print(d)
    {0.1: 4, 0.2: 6}
    

Another way would be to round by an appropriate amount:

    
    
    with open("test.txt") as f:
        keys = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
        d = dict.fromkeys(keys, 0)
        for flt in map(float, f):
            k = round(flt + .05, 1) if flt > .05 else .1
            if flt not in d:
                d[k] += 1
            else:
                d[flt] += 1
    

