gpt4 book ai didi

python - 如何在 Python 中将一系列浮点值合并到直方图中?

转载 作者:太空狗 更新时间:2023-10-29 18:19:44 25 4
gpt4 key购买 nike

我有一组浮点值(总是小于 0)。我想将其放入直方图中,IE。直方图中的每个条包含值范围 [0,0.150)

我的数据是这样的:

0.000
0.005
0.124
0.000
0.004
0.000
0.111
0.112

使用下面的代码,我希望得到如下所示的结果

[0, 0.005) 5
[0.005, 0.011) 0
...etc..

我尝试用我的这段代码进行这样的装箱。但这似乎不起作用。正确的做法是什么?

#! /usr/bin/env python


import fileinput, math

log2 = math.log(2)

def getBin(x):
return int(math.log(x+1)/log2)

diffCounts = [0] * 5

for line in fileinput.input():
words = line.split()
diff = float(words[0]) * 1000;

diffCounts[ str(getBin(diff)) ] += 1

maxdiff = [i for i, c in enumerate(diffCounts) if c > 0][-1]
print maxdiff
maxBin = max(maxdiff)


for i in range(maxBin+1):
lo = 2**i - 1
hi = 2**(i+1) - 1
binStr = '[' + str(lo) + ',' + str(hi) + ')'
print binStr + '\t' + '\t'.join(map(str, (diffCounts[i])))

~

最佳答案

如果可能,不要重新发明轮子。 NumPy 拥有您需要的一切:

#!/usr/bin/env python
import numpy as np

a = np.fromfile(open('file', 'r'), sep='\n')
# [ 0. 0.005 0.124 0. 0.004 0. 0.111 0.112]

# You can set arbitrary bin edges:
bins = [0, 0.150]
hist, bin_edges = np.histogram(a, bins=bins)
# hist: [8]
# bin_edges: [ 0. 0.15]

# Or, if bin is an integer, you can set the number of bins:
bins = 4
hist, bin_edges = np.histogram(a, bins=bins)
# hist: [5 0 0 3]
# bin_edges: [ 0. 0.031 0.062 0.093 0.124]

关于python - 如何在 Python 中将一系列浮点值合并到直方图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1721273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com