0

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)
1
  • 1
    please provide an explicit minimal (unambiguous) example of input/expected output Commented Sep 6, 2022 at 6:34

3 Answers 3

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

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]

1 Comment

Oh I hadn't read about np.hstack or np.newaxis. Got more reading to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.