【问题标题】:Divide a array into multiple (individual) arrays based on a bin size in python根据python中的bin大小将数组划分为多个(单个)数组
【发布时间】:2012-07-02 00:25:15
【问题描述】:

我正在读取一个包含如下值的文件:

-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

如何根据第 1 列中的值将其拆分为单独的数组,bin 宽度为 0.1?

我希望我的输出是这样的:

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]]

【问题讨论】:

  • 这与您的other question 非常相似。那里的答案都没有帮助你吗?
  • 我尝试将解决方案应用于我之前的问题,但没有帮助。我需要它用于 2 列。这很难解决。

标签: python


【解决方案1】:

这是一个使用 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    

要获取特定的存储桶(如 .3),只需执行以下操作:

x = dictionary[0.3]

x = dictionary.get(0.3, [])

如果您只想为空存储桶返回一个空列表。

【讨论】:

    猜你喜欢
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多