Python将2d numpy数组与1d数组对应相乘

Python将2d numpy数组与1d数组对应相乘

给定两个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:使用 axis as none

# 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]]

方法三:使用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]]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Numpy 示例