如何将一个向量添加到给定的 Numpy 数组?
在这个问题中,我们必须将一个向量/数组添加到一个 numpy 数组中。我们将定义 numpy 数组和向量,并将它们相加得到结果数组
算法
Step 1: Define a numpy array. Step 2: Define a vector. Step 3: Create a result array same as the original array. Step 4: Add vector to each row of the original array. Step 5: Print the result array.
示例代码
import numpy as np original_array = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) print("Original Array: \n", original_array) vector = np.array([1,1,0]) print("\nVector: ", vector) result = np.empty_like(original_array) for i in range(4): result[i,:] = original_array[i,:] + vector print("\nResult: \n", result)
输出
Original Array: [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] Vector: [1 1 0] Result: [[ 2 3 3] [ 5 6 6] [ 8 9 9] [11 12 12]]
解释
语句 result = np.empty_like(original_array) 创建了一个与 original_array 具有相同维度大小的空数组 'result'
广告