Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to group a data in python

Tags:

python

I have a file with data like:

  Entry   Freq.
    2     4.5
    3     3.4
    5     4.9
    8     9.1
    12    11.1
    16    13.1
    18    12.2
    22    11.2

now the problem I am trying to solve is: I want to make it a grouped data (with range 10) based on the Entry and want to add up the frequencies falling within the range. e.g. for above table if I group it then it should be like:

    Range   SumFreq.
     0-10    21.9(i.e. 4.5 + 3.4 + 4.9 + 9.1)
     11-20   36.4

I reached upto column separation with following code but can't be able to perform range separation thing: my code is:

inp = ("c:/usr/ovisek/desktop/file.txt",'r').read().strip().split('\n')
for line in map(str.split,inp):
    k = int(line[0])
    l = float(line[-1])

so far is fine but how could I be able to group the data in 10 range.

like image 814
Ovisek Avatar asked Aug 10 '26 12:08

Ovisek


1 Answers

One way would be to [ab]use the fact that integer division will give you the right bins:

import collections
bin_size = 10
d = collections.defaultdict(float)
for line in map(str.split,inp):
    k = int(line[0])
    l = float(line[-1])
    d[bin_size * (k // bin_size)] += l
like image 78
wim Avatar answered Aug 13 '26 02:08

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!