有没有更好的方法来计算进入间隔的频率?

Is there a better way to count frequencies of getting in the intreval?

所以,我有一个 numpy 数组,我想计算元素在特定时间间隔内出现的频率。 例如,

array = np.array([0, 1, 1, 1, 2, 3, 4, 5]) 
intervals = np.array([0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5.])
result = {0.5: 0.125, 1.5: 0.375, 2.5: 0.125, 3.5: 0.125, 4.5: 0.125}

我的代码工作正常,但对我来说看起来很乱

import numpy as np
from collections import Counter

def freqs(arr):
    #defining our intervals
    intervals = np.arange(round(np.min(arr)), round(np.max(arr))+0.5, 0.5)
    frequency = list()

    #going through every number in array, if smaller then interval's value, appending interval's value
    for arr_i in arr:
        for intr_j in intervals:
            if arr_i < intr_j:
                frequency.append(intr_j)
                break

    #counting intervals' values
    dic = dict(Counter(frequency))
    #divide dic's values by lenghth of an array
    freqs = dict(zip(list(dic.keys()), (np.array(list(dic.values())))/len(arr)))

    return freqs

我不喜欢的部分是我们将字典的值除以数组的长度,并使用大量构造来声明新字典。但是我们所做的一切只是将值除以某个数字。

我可以得到与您使用 np.histogram 函数相同的结果。

result, _ = np.histogram(array, bins=intervals)
result = result / len(array)
filter_result = result[np.where(result > 0)]
print(filter_result)

[0.125 0.375 0.125 0.125 0.125 0.125]

希望这能给你一些想法。

改进@YOLO 的回答

>>> c, b = np.histogram(array, bins=intervals)
>>> {i:j for i,j in zip(b[1::2], c[0::2]/len(array))}
{0.5: 0.125, 1.5: 0.375, 2.5: 0.125, 3.5: 0.125, 4.5: 0.125}

您可以使用:

arr = np.logical_and(intervals[:-1:2] <= array[:,None],
                     array[:,None] < intervals[1::2])
dict(zip(intervals[1::2], arr.sum(axis=0) / len(array)))

输出:

{0.5: 0.125, 1.5: 0.375, 2.5: 0.125, 3.5: 0.125, 4.5: 0.125}