numpy array product driving me mad

Manolo Martínez manolo at austrohungaro.com
Fri Mar 20 09:11:45 EDT 2015


On 03/20/15 at 01:46pm, Mr. Twister wrote:
 
> I have two numpy arrays:
> 
> >>> P
> array([[[ 2,  3],
>         [33, 44],
>         [22, 11],
>         [ 1,  2]]])
> >>> R
> array([0, 1, 2, 3])
> 
> the values of these may of course be different. The important fact is that:
> 
> >>> P.shape
> (1, 4, 2)
> >>> R.shape
> (4,)
> 
> where the number 4 in the shape of both P and R may be another number as well
> (same on both).
> 
> 
> What I'd like to get is a new array Q with same shape as P so that the nth pair
> of Q is the nth pair of P multiplied by the nth element of R. I.e., in the above
> case it should produce:
> 
> >>> Q
> array([[[ 0,  0],
>         [33, 44],
>         [44, 22],
>         [ 3,  6]]])
> 
> 
> Is there a direct, single expression command to get this result? 

I think that you want 

    P * R[;,None]

Read about broadcasting
(http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) for an
explanation. I'm never sure I understand it myself :)

Manolo
 



More information about the Python-list mailing list