3

行と列の座標を知ることで、numpy 配列に値を代入する小さなスクリプトを作成しました。

gridarray = np.zeros([3,3])
gridarray_counts = np.zeros([3,3])

cols = np.random.random_integers(0,2,15)
rows = np.random.random_integers(0,2,15)
data = np.random.random_integers(0,9,15)

for nn in np.arange(len(data)):
    gridarray[rows[nn],cols[nn]] += data[nn]
    gridarray_counts[rows[nn],cols[nn]] += 1

実際、同じグリッドセルに格納されている値の数と、それらの合計が何であるかがわかります。ただし、長さが100000以上の配列でこれを実行すると、かなり遅くなります。forループを使わない別の方法はありますか?

これに似たアプローチは可能ですか?これがまだ機能していないことはわかっています。

gridarray[rows,cols] += data
gridarray_counts[rows,cols] += 1
4

2 に答える 2

2

私はこれを使用bincountしますが、今のところ bincount は 1darrays しか使用しないため、次のような独自の ndbincout を作成する必要があります。

def ndbincount(x, weights=None, shape=None):
    if shape is None:
        shape = x.max(1) + 1

    x = np.ravel_multi_index(x, shape)
    out = np.bincount(x, weights, minlength=np.prod(shape))
    out.shape = shape
    return out

次に、次のことができます。

gridarray = np.zeros([3,3])

cols = np.random.random_integers(0,2,15)
rows = np.random.random_integers(0,2,15)
data = np.random.random_integers(0,9,15)

x = np.vstack([rows, cols])
temp = ndbincount(x, data, gridarray.shape)
gridarray = gridarray + temp
gridarray_counts = ndbincount(x, shape=gridarray.shape)
于 2013-04-18T17:59:09.677 に答える
0

これを直接行うことができます:

gridarray[(rows,cols)]+=data
gridarray_counts[(rows,cols)]+=1
于 2013-04-18T17:50:41.147 に答える