我有一組float(總是小於0)的值。我想把它分成直方圖, 我,例如。直方圖各條包含的值範圍[0,0.150)Howto將一系列float值轉換爲Python中的直方圖?
我的數據是這樣的:
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])))
〜
好了, 「你所期望的......」,如果有)定義爲0,0.005範圍(右開),示例[0.005,0.011) (關閉左側) 那麼輸出應該是: [0,0.005)4 [0.005,0.011)1 etc ... – Gacek 2009-11-12 10:56:36
「似乎不工作?」任何具體的投訴?或者你是否期望每個人都必須運行它並嘗試猜測你不喜歡輸出的內容? – 2009-11-12 10:58:00
爲避免重新發明輪子,尤其是在下一步繪製直方圖時:應考慮使用處理所有這些的Matplotlib框架。 – RedGlyph 2009-11-12 12:13:23