Extremely new and pretty confused using python.
I have two arrays. Array 1 is 2x2 and array 2 is 2x3. I'm trying to multiply the two arrays to create array 3, and the 3rd column in array 3 is to repeat the 2 numbers in the 3rd column from array 2. I'm not sure if there's a specific way to do that, so I was thinking I'd slice array 2 to make it 2x2, multiply array1 with array2slice. This would give me a 2x2 array with the multiplied values. All I would need to do is add on the removed 3rd column (eg 1 and 5). I was thinking to do that with np.append but that doesn't seem to work (I'm sure to be doing it wrong).
Any help would be appreciated.
array2Slice = np.array(array2[0:2, 0:2])
WIParray3 = np.multiply(array1,array2Slice)
array3 = np.append(WIParray3, [1],[5],axis = 1)
CodePudding user response:
I think this might be a syntax error. Looking at https://numpy.org/doc/stable/reference/generated/numpy.append.html i would suggest:
array3 = np.append(WIParray3, [[1],[5]],axis = 1)
Also providing an error message might help solve your problem :)
CodePudding user response:
Here is the code.
Arr1 = np.array([[1,2],[3,4]]) # 2x2 array
Arr2 = np.array([[5,6,7],[8,9,10]]) # 2x3 array
multiplyed = np.multiply(Arr1,Arr2[0:2,0:2] )
Arr3 = np.append(multiplyed ,[ [Arr2[0,2]] , [Arr2[1,2] ]] , axis = 1)
CodePudding user response:
You can solve this in one line with:
array3 = np.hstack([array1 * array2[:2, :2], array2[:, np.newaxis, 2]])
Where np.hstack
takes a sequence of arrays and concatenates them column wise. All the arrays must have the same shape along all but the second axis, that's why a np.newaxis
has to be added to the column.
Caution: the operator *
(equivalent to np.multiply
) multiplies element by element. If you want a matrix multiplication use @
(equivalent to np.matmul
).
A simpler but longer way would be:
array3 = np.zeros((2, 3), dtype=array2.dtype)
array3[:2, :2] = array1 * array2[:2, :2]
array3[:, 2] = array2[:, 2]