Skip to content Skip to sidebar Skip to footer

Weighted Numpy Bincount For 2d Ids Array And 1d Weights

I am using numpy_indexed for applying a vectorized numpy bincount, as follows: import numpy as np import numpy_indexed as npi rowidx, colidx = np.indices(index_tri.shape) (cols, ro

Solution 1:

Inspired by this post -

def bincount2D(id_ar_2D, weights_1D):
    # Inputs : 2D id array, 1D weights array
    
    # Extent of bins per col
    n = id_ar_2D.max()+1
    
    N = len(id_ar_2D)
    id_ar_2D_offsetted = id_ar_2D + n*np.arange(N)[:,None]
    
    # Finally use bincount with those 2D bins as flattened and with
    # flattened b as weights. Reshaping is needed to add back into "a".
    ids = id_ar_2D_offsetted.ravel()
    W = np.tile(weights_1D,N)
    return np.bincount(ids, W, minlength=n*N).reshape(-1,n)

out = bincount2D(index_tri, weights)

Post a Comment for "Weighted Numpy Bincount For 2d Ids Array And 1d Weights"