Search code examples
pythondictionarybinning

Binning variable length lists in python


I have a dictionary d with 100 keys where the values are variable length lists, e.g.

 In[165]: d.values()[0]
 Out[165]: 
 [0.0432,
  0.0336,
  0.0345,
  0.044,
  0.0394,
  0.0555]

 In[166]: d.values()[1]
 Out[166]: 
 [0.0236,
  0.0333,
  0.0571]

Here's what I'd like to do: for every list in d.values(), I'd like to organize the values into 10 bins (where a value gets tossed into a bin if it satisfies the criteria, e.g. is between 0.03 and 0.04, 0.04 and 0.05, etc.).

What'd I'd like to end up with is something that looks exactly like d, but instead of d.values()[0] being a list of numbers, I'd like it to be a list of lists, like so:

 In[167]: d.values()[0]
 Out[167]:
 [[0.0336,0.0345,0.0394],
  [0.0432,0.044],
  [0.0555]]

Each key would still be associated with the same values, but they'd be structured into the 10 bins.

I've been going crazy with nested for loops and if/elses, etc. What is the best way to go about this?

EDIT: Hi, all. Just wanted to let you know I resolved my issues. I used a variation of @Brent Washburne's answer. Thanks for the help!


Solution

  • def bin(values):
        bins = [[] for _ in range(10)]    # create ten bins
        for n in values:
            b = int(n * 100)              # normalize the value to the bin number
            bins[b].append(n)             # add the number to the bin
        return bins
    
    d =  [0.0432,
      0.0336,
      0.0345,
      0.044,
      0.0394,
      0.0555]
    print bin(d)
    

    The result is:

    [[], [], [], [0.0336, 0.0345, 0.0394], [0.0432, 0.044], [0.0555], [], [], [], []]