Python numpy broadcasting 3 dimensions (multiple weighted sums)
I have become kind of used to cast with 2-dimensional arrays, but I can't seem to get around this 3D thing I want to do.
I have two two dimensional arrays:
>>> a = np.array([[0.01,.2,.3,.4],[.2,.03,.4,.5],[.9,.8,.7,.06]])
>>> b= np.array([[1,2,3],[3.,4,5]])
>>> a
array([[ 0.01, 0.2 , 0.3 , 0.4 ],
[ 0.2 , 0.03, 0.4 , 0.5 ],
[ 0.9 , 0.8 , 0.7 , 0.06]])
>>> b
array([[ 1., 2., 3.],
[ 3., 4., 5.]])
Now, what I want is the sum of all rows in a, where each row is weighted by the values โโof the column in b. So, I want 1. * a[0,:] + 2. * a[1,:] + 3. * a[2,:]
the same thing for the second line b.
So, I know how to do it step by step:
>>> (np.array([b[0]]).T * a).sum(0)
array([ 3.11, 2.66, 3.2 , 1.58])
>>> (np.array([b[1]]).T * a).sum(0)
array([ 5.33, 4.72, 6. , 3.5 ])
But I have a feeling that if I knew how to properly cast the two as 3D arrays, I could get the result I want in one go. Result:
array([[ 3.11, 2.66, 3.2 , 1.58],
[ 5.33, 4.72, 6. , 3.5 ]])
I guess it shouldn't be too hard ..?!?
+3
source to share