[Numpy-discussion] simple array multiplication question
David Warde-Farley
dwf@cs.toronto....
Mon Oct 12 23:40:18 CDT 2009
On 12-Oct-09, at 11:53 PM, per freem wrote:
> what i want to do is pick the columns l of p, and multiply each one by
> the numbers in s. the first step, picking columns l of p, is simply:
>
> cols = p[arange(3), l]
This isn't picking columns of p, this is picking the times at (0, 0),
(1, 0), and (2, 1). Is this what you meant?
In [36]: p[arange(3), [0,0,1]]
Out[36]: array([ 0.2, 0.5, 0.7])
In [37]: p[:, [0,0,1]]
Out[37]:
array([[ 0.2, 0.2, 0.8],
[ 0.5, 0.5, 0.5],
[ 0.3, 0.3, 0.7]])
In [38]: p[arange(3), [0,0,1]] * s.reshape(3,1)
Out[38]:
array([[ 2., 5., 7.],
[ 4., 10., 14.],
[ 6., 15., 21.]])
In [41]: p[:, [0,0,1]] * s.reshape(3,1)
Out[41]:
array([[ 2., 2., 8.],
[ 10., 10., 10.],
[ 9., 9., 21.]])
Notice the difference.
> then i want to multiply each one by the numbers in s, and i do it
> like this:
>
> cols * s.reshape(3,1)
>
> this seems to work, but i am concerned that it might be inefficient.
> is there a cleaner way of doing this? is 'arange' operation necessary
> to reference all the 'l' columns of p?
That's about as efficient as it gets, I think.
> also, is the reshape operation
> expensive?
No. It will return a view, rather than make a copy.
You could also do cols * s[:, np.newaxis], equivalently.
David
More information about the NumPy-Discussion
mailing list