Heinz
Heinz

Reputation: 2467

Numpy: expanding subarray of a larger array

I have a Numpy array like this,

[[1 2 3
  2 0 0
  3 0 0]]

and I want to turn it into this form,

[[1 2 2 3 3
  2 0 0 0 0
  2 0 0 0 0
  3 0 0 0 0
  3 0 0 0 0]]

My idea is to extract the sub-array contains zero from the original array, and use Kronecker product to get the sub-array, which is in the array I want. But I have no idea to get the first row and column of the output array.

How to achieve this goal? Please give me any suggestions.

Upvotes: 0

Views: 227

Answers (1)

Alex Riley
Alex Riley

Reputation: 176750

Another way would be to use np.repeat. If arr is your 3x3 array:

>>> arr.repeat([1, 2, 2], axis=0).repeat([1, 2, 2], axis=1)
array([[1, 2, 2, 3, 3],
       [2, 0, 0, 0, 0],
       [2, 0, 0, 0, 0],
       [3, 0, 0, 0, 0],
       [3, 0, 0, 0, 0]])

For example, arr.repeat([1, 2, 2], axis=0) means that the first row of arr is repeated once, the second row is repeated twice and the third row is repeated three times.

The same thing is then done for the columns.

Upvotes: 3

Related Questions