我已经在Python中创建了一个函数,用于计算数据的直方图。它有一个参数bins,指定分割的数量。
我以下提供了我的代码,并且数据在链接https://gist.github.com/mesarvagya/11367012上。
现在将两个函数的 bins = 10 的结果比较如下:
我以下提供了我的代码,并且数据在链接https://gist.github.com/mesarvagya/11367012上。
import numpy as np
def histogram_using_numpy(filename, bins=10):
datas = np.loadtxt(filename, delimiter=" ", usecols=(0,))
hist,bin_edges = np.histogram(datas, bins)
return hist
print "from numpy %s" % histogram_using_numpy("ex.txt", bins=10)
def histogram_using_list(filename, bins=10, take_col=0):
f = open(filename,"r")
data = []
for item in f.readlines():
data.append(float(item.split()[take_col]))
f.close()
mi,ma = min(data), max(data)
bin_length = (ma-mi)/bins
def get_count(lis,low,diff):
count = 0
for item in lis:
if item >= low and item < low + diff:
count += 1
return count
tot = []
for i in np.arange(mi, ma, bin_length):
tot.append(get_count(data,i, bin_length))
return tot
print "From my function %s " % histogram_using_list("ex.txt", bins=10)
现在将两个函数的 bins = 10 的结果比较如下:
from numpy [10 19 20 28 15 16 14 11 5 12]
From my function [10, 19, 20, 28, 16, 15, 14, 11, 5, 12]
这是错误的。而对于 bins = 15,我得到了以下结果:
from numpy [ 7 4 18 19 5 24 8 10 13 6 13 6 5 1 11]
From my function [7, 4, 18, 19, 10, 19, 8, 10, 13, 10, 9, 6, 5, 1, 11]
这也是不正确的。假设Numpy是正确的,我的代码有什么问题吗?
np.histogram
呢?! - Hadi