-2

我想根据范围列表汇总数据列表。这个想法是我想制作最终结果的直方图。我知道 collections.Counter 但还没有看到我们或其他内置的人来生成团块。我已经写出了长表格,但希望有人能提供更有效的东西。

def min_to_sec(val):
    ret_val = 60 * int(val)
    return ret_val

def hr_to_sec(val):
    ret_val = 3600 * int(val)
    return ret_val

def histogram(y_lst):
    x_lst = [   10,
                20,
                30,
                40,
                50,
                60,
                90,
                min_to_sec(2),
                min_to_sec(3),
                min_to_sec(4),
                min_to_sec(5),
                min_to_sec(10),
                min_to_sec(15),
                min_to_sec(20),
            ]

    results = {}    
    for y_val in y_lst:
        for x_val in x_lst:
            if y_val < x_val:
                results[ str(x_val) ] = results.get( str(x_val), 0) + 1
                break
        else:        
            results['greater'] = results.get('greater', 0) + 1
    return results

更新以包含所需示例输出的示例:

所以如果我的 x_lst 和 y_list 是:

x_lst = [10,20,30,40]
y_lst = [1,2,3,15,22,27,40]

我想要一个类似于 Counter 的返回值:

{
    10:3,
    20:1,
    30:2,
}

因此,虽然我上面的代码有效,因为它是一个嵌套的 for 循环,但它很慢,我希望有一种方法可以使用像 collections.Count 这样的东西来执行这个“聚集”操作。

4

2 回答 2

0

Have you considered using pandas? You could put y_lst into a DataFrame and pretty easily make a histogram.

Assuming you have matplotlib and pylab imported...

import pandas as pd
data = pd.DataFrame([1, 2, 3, 15, 22, 27, 40])
data[0].hist(bins = 4)

That would give you the histogram you describe above. However, once the data is in a pandas DataFrame it's not too challenging to slice it up however you'd like.

于 2013-09-13T17:16:04.247 回答
0

您可以使用collections.Counter对列表中的元素进行这种计数:

In [1]: from collections import Counter

In [2]: Counter([1, 2, 10, 1, 2, 100])
Out[2]: Counter({1: 2, 2: 2, 100: 1, 10: 1})

您可以使用以下方法更简单地增加计数器:

results['foo'] += 1

为了只计算不等式之前的那些,您可以使用itertools.takewhile

In [3]: from itertools import takewhile 

In [4]: Counter(takewhile(lambda x: x < 10, [1, 2, 10, 1, 2, 100]))
Out[4]: Counter({1: 1, 2: 1})

但是,这不会跟踪那些已经超出拍摄时间的人。

于 2013-09-12T14:09:58.187 回答