0

I am reading a file that contains values like this:

-0.68285 -6.919616
-0.7876 -14.521115
-0.64072 -43.428411
-0.05368 -11.561341
-0.43144 -34.768892
-0.23268 -10.793603
-0.22216 -50.341101
-0.41152 -90.083377
-0.01288 -84.265557
-0.3524 -24.253145

How do i split this into individual arrays based on the value in column 1 with a bin width of 0.1?

i want my output something like this:

array1=[[-0.05368, -11.561341],[-0.01288, -84.265557]]
array2=[[-0.23268, -10.79360] ,[-0.22216, -50.341101]]
array3=[[-0.3524, -24.253145]]
array4=[[-0.43144, -34.768892], [-0.41152, -90.083377]]
array5=[[-0.68285, -6.919616],[-0.64072, -43.428411]]
array6=[[-0.7876, -14.521115]]
user1492449
  • 91
  • 1
  • 1
  • 4
  • 2
    This is very similar to your [other question](http://stackoverflow.com/questions/11270991/divide-a-list-into-multiple-lists-based-on-a-bin-size). Did none of the answers there help you? – Ned Batchelder Jul 01 '12 at 03:15
  • I tried to apply the the solution for my previous questions, but it was not helpful. I need it for 2 columns. which is tricky to solve. – user1492449 Jul 01 '12 at 23:50

1 Answers1

0

Here's a simple solution using Python's round function and dictionary class:

lines = open('some_file.txt').readlines()

dictionary = {}
for line in lines:
    nums = line[:-1].split(' ')     #remove the newline and split the columns
    k = round(float(nums[0]), 1)    #round the first column to get the bucket
    if k not in dictionary:         
        dictionary[k] = []          #add an empty bucket
    dictionary[k].append([float(nums[0]), float(nums[1])])
                                    #add the numbers to the bucket
print dictionary    

To get a particular bucket (like .3), just do:

x = dictionary[0.3]

or

x = dictionary.get(0.3, [])

if you just want an empty list returned for empty buckets.

Josh Buell
  • 606
  • 5
  • 12