2

I have a numpy array arrayBig

10  5 27 30 34
2  34 23  2  3 
2  3  43 12 23
2  24 34  2 34

And I have a numpy array arraySmall

1 0 0 
0 1 1
1 1 0

What I want is a numpy array arrayNew

34 0 0 
0 43 12
24 34 0

I know my arraySmall has the shape (3,3) and is located at index (1 1) in arrayBig. How can I get arrayNew with Numpy?

2 Answers 2

2
>>> import numpy as np
>>> arrayBig = np.array([
...     [10,  5, 27, 30, 34],
...     [2,  34, 23,  2,  3],
...     [2,   3, 43, 12, 23],
...     [2,  24, 34,  2, 34],
... ])
>>> arraySmall = np.array([
...     [1, 0, 0],
...     [0, 1, 1],
...     [1, 1, 0],
... ])
>>> arrayBig[1:4, 1:4] * arraySmall
array([[34,  0,  0],
       [ 0, 43, 12],
       [24, 34,  0]])
Sign up to request clarification or add additional context in comments.

Comments

1

I recently learned about advanced boolean indexing. I'm not sure if it's any better than the other answer but you can do:

>>> a = np.array([[1,2,3],[4,5,6]])
>>> b = np.array([[1,0],[0,1]])
>>> c = b == 0
>>> d = a[0:b.shape[0],0:b.shape[1]]
>>> d[c] = 0
>>> d
array([[1, 0],
       [0, 5]])

Comments

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.