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.

user21398
  • 419
  • 6
  • 13

1 Answers1

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]])
Akavall
  • 82,592
  • 51
  • 207
  • 251