简体   繁体   中英

Multiplying a 2D (5x3) array by a 1D (5x1) array in python

I want to ask a question about multiplying 2D arrays by a 1D array.

I have the following 2 numpy arrays:

>> array1_test
array([14.0067, 12.0107, 12.0107, 15.9994, 12.0107])

>> array2_test
array([[49.725, 20.724, 59.915],
       [51.168, 20.935, 60.26 ],
       [51.32 , 21.167, 61.757],
       [50.327, 21.247, 62.472],
       [51.732, 22.136, 59.483]])

I want to multiply each row in array2_test by the corresponding float in the position of array1_test .

I tried this using a while loop:

i = 0
while i < len(array2_test):
    print(array1_test[i] * array2_test[i])
    i += 1

which yields my expected result:

[696.4831575 290.2748508 839.2114305]
[614.5634976 251.4440045 723.764782 ]
[616.389124  254.2304869 741.7447999]
[805.2018038 339.9392518 999.5145168]
[621.3375324 265.8688552 714.4324681]

but I would like to store these in an array of the form:

array([[696.4831575 290.2748508 839.2114305],
[614.5634976 251.4440045 723.764782 ],
[616.389124  254.2304869 741.7447999],
[805.2018038 339.9392518 999.5145168],
[621.3375324 265.8688552 714.4324681]])

I tried to do the following:

i = 0
mylist = []
while i < len(array2_test):
    mylist += (array1_test[i] * array2_test[i])
    i += 1

but that yields no result.

How can such a result be achieved?

My intuition was to convert the multiplication result into a list and append to mylist but as I am required to return an array, I was wondering whether a shorter solution was possible.

The trick is to turn the 1-D array of shape (5,) into a 2-D array of shape (5, 1) by slicing with None (which creates a new axis). This allows you to simply multiply the arrays together and let NumPy handle the rest:

>>> array2_test * array1_test[:, None]
array([[696.4831575, 290.2748508, 839.2114305],
       [614.5634976, 251.4440045, 723.764782 ],
       [616.389124 , 254.2304869, 741.7447999],
       [805.2018038, 339.9392518, 999.5145168],
       [621.3375324, 265.8688552, 714.4324681]])

reshape is enough here:

array2_test * array1_test.reshape((5,1)

gives as expected:

array([[696.4831575, 290.2748508, 839.2114305],
       [614.5634976, 251.4440045, 723.764782 ],
       [616.389124 , 254.2304869, 741.7447999],
       [805.2018038, 339.9392518, 999.5145168],
       [621.3375324, 265.8688552, 714.4324681]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM