0

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.

1
  • I adjusted the title as you suggested in your question - do feel free to change it back or improve it further if you feel it doesn't quite fit with what you're asking. Commented Feb 5, 2015 at 15:29

1 Answer 1

3

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.

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

2 Comments

Thanks for replying me with this helpful answer, but if there are many rows, say, 20 in the input array, that will be inconvenient to get the output array via using these codes. And I'm still thinking about how to solve this problem.
@Heinz: if arr has 20 rows, you could always do, for example, arr.repeat([1]+[2]*19, axis=0) to repeat each row after the first row two times.

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.