📜  Python|将对应于 1d 数组的 2d numpy 数组相乘

📅  最后修改于: 2022-05-13 01:54:20.580000             🧑  作者: Mango

Python|将对应于 1d 数组的 2d numpy 数组相乘

给定两个 numpy 数组,任务是将 2d numpy 数组与 1d numpy 数组相乘,每一行对应于 numpy 中的一个元素。让我们讨论给定任务的一些方法。

方法 #1:使用 np.newaxis()

# Python code to demonstrate
# multiplication of 2d array
# with 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]
  
# printing result
print("New resulting array: ", result)
输出:
initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [[ 0  0  0]
 [ 4  8 10]
 [ 3  6  9]]


方法#2:使用轴作为无

# Python code to demonstrate
# multiplication of 2d array
# with 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]
  
# printing result
print("New resulting array: ", result)
输出:
initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [[ 0  0  0]
 [ 4  8 10]
 [ 3  6  9]]


方法 #3:使用 transpose()

# python code to demonstrate
# multiplication of 2d array
# with 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
  
# printing result
print("New resulting array: ", result)
输出:
initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [[ 0  0  0]
 [ 4  8 10]
 [ 3  6  9]]