Howto bin series of float values into histogram in Python?(如何在 Python 中将一系列浮点值合并到直方图中?)
问题描述
我有一组浮点值(总是小于 0).我想将其放入直方图中,IE.直方图中的每个条形都包含值范围 [0,0.150)
I have set of value in float (always less than 0). Which I want to bin into histogram, i,e. each bar in histogram contain range of value [0,0.150)
我拥有的数据如下所示:
The data I have looks like this:
0.000
0.005
0.124
0.000
0.004
0.000
0.111
0.112
在我下面的代码中,我希望得到看起来像这样的结果
Whith my code below I expect to get result that looks like
[0, 0.005) 5
[0.005, 0.011) 0
...etc..
我试图用我的这段代码做这样的分箱.但它似乎不起作用.正确的做法是什么?
I tried to do do such binning with this code of mine. But it doesn't seem to work. What's the right way to do it?
#! /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 + ' ' + ' '.join(map(str, (diffCounts[i])))
~
推荐答案
如果可能,不要重新发明轮子.NumPy 拥有您需要的一切:
When possible, don't reinvent the wheel. NumPy has everything you need:
#!/usr/bin/env python
import numpy as np
a = np.fromfile(open('file', 'r'), sep='
')
# [ 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 中将一系列浮点值合并到直方图中


- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01