Home > Mobile >  Use numpy bincount with weights for 2d array
Use numpy bincount with weights for 2d array

Time:03-27

Suppose I have the following 1d numpy arrays

>>> x = np.array([1,2,3,4,5,6])
>>> y = np.array([10,20,30,40,50,60])

and bins

>>> bins = np.array([0,0,1,1,2,3])

Then I may use bincount for each array like:

>>> np.bincount(bins, weights=x)
array([ 3.,  7.,  5.,  6.])
>>> np.bincount(bins, weights=y)
array([ 30.,  70.,  50.,  60.])

Can I perform both summaries at once ? I tried

>>> np.bincount(np.array([[0,0,1,1,2,3], [0,0,1,1,2,3]]), weights=np.array([[1,2,3,4,5,6], [10,20,30,40,50,60]]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: object too deep for desired array
>>>

and got an error

CodePudding user response:

Nope, it's not possible. And one hint is that there isn't any axis argument that you can pass to bincounts. Your best bet is do them one-at-a-time:

bc = np.array([np.bincount(bins, weights=x), np.bincount(bins, weights=y)])

Or using list-comprehension:

bc = np.array([np.bincount(bins, weights=w) for w in [x, y]])

Output:

>>> bc
array([[ 3.,  7.,  5.,  6.],
       [30., 70., 50., 60.]])

CodePudding user response:

You can simulate bincount with np.add.at:

xy = np.stack([x,y])
n = np.unique(bins).size
out = np.zeros((2,n), dtype=xy.dtype)
np.add.at(out, (slice(None), bins), xy)

output in out:

array([[ 3,  7,  5,  6],
       [30, 70, 50, 60]])
  • Related