2

I have a numpy 2d array:

[[1,1,1],
[1,1,1],
[1,1,1],
[1,1,1]]

How can I get it so that it multiplies the indices from top to bottom with the corresponding values from a 1d array when the row length of the 2d array is smaller than length of 1d array ? For example multiply above with this:

[10, 20, 30, 40]

to get this:

 [[10, 10, 10],
 [20, 20, 20],
 [30, 30, 30]
 [40, 40, 40]]

Probably a duplicate, but I couldnt find exact thing I am looking for. Thanks in advance.

0

1 Answer 1

2

* in numpy does element-wise multiplication, for example multiply 1d array by another 1d array:

In [52]: np.array([3,4,5]) * np.array([1,2,3])
Out[52]: array([ 3,  8, 15])

When you multiply a 2d array by 1d array, same thing happens for every row of 2d array:

In [53]: np.array([[3,4,5],[4,5,6]]) * np.array([1,2,3])
Out[53]:
array([[ 3,  8, 15],
       [ 4, 10, 18]])

For your specific example:

In [66]: ones = np.ones(12, dtype=np.int).reshape(4,3)

In [67]: a = np.array([10, 20, 30, 40])

In [68]: (ones.T * a).T
Out[68]:
array([[10, 10, 10],
       [20, 20, 20],
       [30, 30, 30],
       [40, 40, 40]])
Sign up to request clarification or add additional context in comments.

5 Comments

Had to look up what the .T meant but I see now, thanks a lot.
But wait what happens when your row length is smaller than your 1d Array? Does transpose still work then?
@user21398, If row length is smaller (or larger) than 1d array, you would not be able to multiply.
I see, ill have to rephrase question then. But how could you do it then?
Perfect, thanks for taking the time!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.