python - Row, column assignment without for-loop -
i wrote small script assign values numpy array knowing row , column coordinates:
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) nn in np.arange(len(data)): gridarray[rows[nn],cols[nn]] += data[nn] gridarray_counts[rows[nn],cols[nn]] += 1
in fact, know how many values stored in same grid cell , sum of them. however, performing on arrays of lengths 100000+ getting quite slow. there way without using for-loop?
is approach similar possible? know not working yet.
gridarray[rows,cols] += data gridarray_counts[rows,cols] += 1
i use bincount
this, bincount takes 1darrays you'll need write own ndbincout, like:
def ndbincount(x, weights=none, shape=none): if shape 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
then can do:
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)
Comments
Post a Comment