Pregunta

he puesto de valor en flotador (siempre menor que 0). ¿Qué quiero compartimento dentro de histograma, es decir. cada barra en histograma contiene gama de valor [0,0.150)

Los datos que tengo es el siguiente:

0.000
0.005
0.124
0.000
0.004
0.000
0.111
0.112

Poco Con mi código de abajo espero obtener el resultado que se parece a

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

He intentado hacer hacer tales hurgar en la basura con el código de la mía. Pero no parece funcionar. Cuál es la forma correcta de hacerlo?

#! /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])))

~

¿Fue útil?

Solución

Cuando es posible, no reinventar la rueda. NumPy tiene todo lo que necesita:

#!/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]

Otros consejos

from pylab import *
data = []
inf = open('pulse_data.txt')
for line in inf:
    data.append(float(line))
inf.close()
#binning
B = 50
minv = min(data)
maxv = max(data)
bincounts = []
for i in range(B+1):
    bincounts.append(0)
for d in data:
    b = int((d - minv) / (maxv - minv) * B)
    bincounts[b] += 1
# plot histogram

plot(bincounts,'o')
show()

El primer error es:

Traceback (most recent call last):
  File "C:\foo\foo.py", line 17, in <module>
    diffCounts[ str(getBin(diff)) ] += 1
TypeError: list indices must be integers

¿Por qué estás convirtiendo un int a un str cuando se necesita un str? Arreglar eso, entonces tenemos:

Traceback (most recent call last):
  File "C:\foo\foo.py", line 17, in <module>
    diffCounts[ getBin(diff) ] += 1
IndexError: list index out of range

, ya que sólo ha hecho 5 cubos. No entiendo su esquema de bucketing, pero vamos a hacer que 50 cubos y ver lo que sucede:

6
Traceback (most recent call last):
  File "C:\foo\foo.py", line 21, in <module>
    maxBin = max(maxdiff)
TypeError: 'int' object is not iterable

maxdiff es un valor único de su lista de enteros, así que lo que está haciendo max aquí? Eliminarlo, ahora obtenemos:

6
Traceback (most recent call last):
  File "C:\foo\foo.py", line 28, in <module>
    print binStr + '\t' + '\t'.join(map(str, (diffCounts[i])))
TypeError: argument 2 to map() must support iteration

Efectivamente, estás usando un único valor como segundo argumento a map. Vamos a simplificar las dos últimas líneas de esto:

 binStr = '[' + str(lo) + ',' + str(hi) + ')'
 print binStr + '\t' + '\t'.join(map(str, (diffCounts[i])))

a esto:

 print "[%f, %f)\t%r" % (lo, hi, diffCounts[i])

Ahora se imprime:

6
[0.000000, 1.000000)    3
[1.000000, 3.000000)    0
[3.000000, 7.000000)    2
[7.000000, 15.000000)   0
[15.000000, 31.000000)  0
[31.000000, 63.000000)  0
[63.000000, 127.000000) 3

No estoy seguro de qué más hacer aquí, ya que no entiendo muy bien el bucketing usted está esperando para usar. Parece involucrar potencias binarias, pero no es dar sentido a mí ...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top