[英]Divide a array into multiple (individual) arrays based on a bin size in python
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? 我如何基于第1列中的bin宽度为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]]
Here's a simple solution using Python's round function and dictionary class: 这是使用Python的round函数和字典类的简单解决方案:
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: 要获取特定的存储桶(如.3),只需执行以下操作:
x = dictionary[0.3]
or 要么
x = dictionary.get(0.3, [])
if you just want an empty list returned for empty buckets. 如果您只想为空存储桶返回一个空列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.