5

私はpython / numpyで作業しています。入力データとして、多数の値のペアがあります(x,y)。私は基本的に、特定のデータビン<y>(x)の平均値をプロットしたいと考えています。現時点では、これを達成するために単純なループを使用していますが、これは非常に遅いです。yxfor

# create example data
x = numpy.random.rand(1000)
y = numpy.random.rand(1000)
# set resolution
xbins = 100
# find x bins
H, xedges, yedges = numpy.histogram2d(x, y, bins=(xbins,xbins) )
# calculate mean and std of y for each x bin
mean = numpy.zeros(xbins)
std = numpy.zeros(xbins)
for i in numpy.arange(xbins):
    mean[i] = numpy.mean(y[ numpy.logical_and( x>=xedges[i], x<xedges[i+1] ) ])
    std[i]  = numpy.std (y[ numpy.logical_and( x>=xedges[i], x<xedges[i+1] ) ])

ある種のベクトル化された書き込みをすることは可能ですか?

4

2 に答える 2

15

あなたは不必要に物事を複雑にしています。知っておく必要があるのは、 、 、およびのすべてのビンxについて、そのビンの値の数、それらの値の合計、およびそれらの二乗の合計です。次のように取得できます。nsysy2yxy

>>> n, _ = np.histogram(x, bins=xbins)
>>> sy, _ = np.histogram(x, bins=xbins, weights=y)
>>> sy2, _ = np.histogram(x, bins=xbins, weights=y*y)

それらから:

>>> mean = sy / n
>>> std = np.sqrt(sy2/n - mean*mean)
于 2013-03-18T13:33:37.277 に答える
1

パンダを使用できる場合:

import pandas as pd
xedges = np.linspace(x.min(), x.max(), xbins+1)
xedges[0] -= 0.00001
xedges[-1] += 0.000001
c = pd.cut(x, xedges)
g = pd.groupby(pd.Series(y), c.labels)
mean2 = g.mean()
std2 = g.std(0)
于 2013-03-18T13:50:36.527 に答える