  # Python | Multiply a two-dimensional array corresponding to a 1d array

Arrays | NumPy | Python Methods and Functions

Method # 1: Using np.newaxis ()

 ` # Python code for demonstration ` ` # multiplying a 2d array ` ` # with a 1d array `   ` import ` ` numpy as np `   ` ini_array1 ` ` = ` ` np.array ([[` ` 1 ` `, ` ` 2 ` `, ` ` 3 ` `], [` ` 2 ` `, ` ` 4 ` `, ` ` 5 ` `], [` ` 1 ` `, ` ` 2 ` `, ` ` 3 ` `]]) ` ` ini_array2 ` ` = ` ` np.array ([` ` 0 ` `, ` ` 2 ` `, ` ` 3 ` `]) `   ` # printing initial arrays ` ` print ` ` (` ` "initial array" ` `, ` ` str ` ` (ini_array1)) `   ` # Multiplying arrays ` ` result ` ` = ` ` ini_array1 ` ` * ` ini_array2 [:, np.newaxis]   ` # print result ` ` print ` ` (` ` " New resulting array: "` `, result) `

Exit:

` initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[0 0 0] [4 8 10 ] [3 6 9]] `

Method # 2: Using the Axis As Not

 ` # Python code for demonstration ` ` # multiplying a 2d array ` ` # with a 1d array `   ` import ` ` numpy as np ``   ini_array1 = np.array ([[ 1 , 2 , 3 ], [ 2 , 4 , 5 ], [ 1 , 2 , 3 ]]) ini_array2 = np.array ([ 0 , 2 , 3 ])   # printing initial arrays print ( "initial array" , str (ini_array1))   # Multiplying arrays result = ini_array1 * ini_array2 [:, None ]   # print result print ( "New resulting array:" , result) `

Exit:

` initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[0 0 0] [4 8 10] [3 6 9]] `

Spo ex # 3: Using transpose ()

 ` # Python code for demonstration ` ` # multiplying a 2d array ` ` # with a 1d array `   ` import ` ` numpy as np `   ` ini_array1 ` ` = ` ` np.array ([ [` ` 1 ` `, ` ` 2 ` `, ` ` 3 ` `], [` ` 2 ` `, ` ` 4 ` `, ` ` 5 ` `], [` ` 1 ` `, ` ` 2 ` `, ` ` 3 ` `]]) ` ` ini_array2 ` ` = ` ` np.array ([` ` 0 ` `, ` ` 2 ` `, ` ` 3 ` `]) `   ` # printing initial arrays ` ` print ` ` (` ` "initial array" ` `, ` ` str ` ` (ini_array1)) `   ` # Multiplying arrays ` ` result ` ` = ` ` (ini_array1.T ` ` * ` ` ini_array2) .T `   ` # print result ` ` print ` ` (` ` "New resulting array:" ` `, result) `

Exit:

` initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[0 0 0] [4 8 10] [3 6 9] ] `