Como média de determinadas subseções de tamanho de uma lista no Python?
Pergunta
Eu gostaria de tirar mordidas de uma lista (ou matriz) de um determinado tamanho, retornar a média para essa mordida e depois passar para a próxima mordida e fazer isso novamente. Existe alguma maneira de fazer isso sem escrever um loop para?
In [1]: import numpy as np
In [2]: x = range(10)
In [3]: np.average(x[:4])
Out[3]: 1.5
In [4]: np.average(x[4:8])
Out[4]: 5.5
In [5]: np.average(x[8:])
Out[5]: 8.5
Estou procurando algo como, np.average (x [: biteSize = 4]) para retornar: [1.5,5.5,8.5].
Eu olhei para cortar matrizes e passar por matrizes, mas não encontrei nada que faça algo como eu quero ter acontecido.
Solução
[np.average(x[i:i+4]) for i in xrange(0, len(x), 4) ]
Outras dicas
The grouper
itertools
recipe can help.
Using numpy, you can use np.average
with the axis
keyword:
import numpy as np
x=np.arange(12)
y=x.reshape(3,4)
print(y)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(np.average(y,axis=1))
# [ 1.5 5.5 9.5]
Note that to reshape x
, I had to make x
start with a length evenly divisible by the group size (in this case 4).
If the length of x
is not evenly divisible by the group size, then could create a masked array and use np.ma.average
to compute the appropriate average.
For example,
x=np.ma.arange(12)
y=x.reshape(3,4)
mask=(x>=10)
y.mask=mask
print(y)
# [[0 1 2 3]
# [4 5 6 7]
# [8 9 -- --]]
print(np.ma.average(y,axis=1))
# [1.5 5.5 8.5]