Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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]])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top