Assigning identical array indices at once in Python/Numpy -
i want find fast way (without loop) in python assign reoccuring indices of array. desired result using loop:
import numpy np a=np.arange(9, dtype=np.float64).reshape((3,3)) # array indices: [2,3,4] identical. px = np.uint64(np.array([0,1,1,1,2])) py = np.uint64(np.array([0,0,0,0,0])) # array added @ array indices (may contain random numbers). x = np.array([.1,.1,.1,.1,.1]) m in np.arange(len(x)): a[px[m]][py[m]] += x print %[[ 0.1 1. 2.] %[ 3.3 4. 5.] %[ 6.1 7. 8.]] when try add x a @ indices px,py not same result (3.3 vs. 3.1):
a[px,py] += x print %[[ 0.1 1. 2.] %[ 3.1 4. 5.] %[ 6.1 7. 8.]] is there way numpy? thanks.
yes, can done, little tricky:
# convert yourmulti-dim indices flat indices flat_idx = np.ravel_multi_index((px, py), dims=a.shape) # extract unique indices , position unique_idx, idx_idx = np.unique(flat_idx, return_inverse=true) # aggregate repeated indices deltas = np.bincount(idx_idx, weights=x) # sum them array a.flat[unique_idx] += deltas
Comments
Post a Comment