所以,我有一个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
我不喜欢的部分是,我们用数组的长度来划分字典的值,并使用许多构造来声明新字典。但我们所做的一切只是将值除以某个数。你知道吗
改进@YOLO的答案
您可以使用:
输出:
我可以得到与使用
np.histogram
函数相同的结果。你知道吗希望这能给你一些想法。你知道吗
相关问题 更多 >
编程相关推荐