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

2024-04-20 13:49:54 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有一个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

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


Tags: inimportnumpynpcounter数组arraylist
3条回答

改进@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}

我可以得到与使用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]

希望这能给你一些想法。你知道吗

相关问题 更多 >