在这个问题上,我们必须将一个向量/数组添加到一个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)