1

I have the following array:

first = array([[4, 5],
               [7, 9]])

And I would like to duplicate every element i into every following i + 1 row and i + 1 column.

My output should look like this:

array([[4, 4, 5, 5],
       [4, 4, 5, 5],
       [7, 7, 9, 9],
       [7, 7, 9, 9]])
1
  • I can't think of any clever way without doing it element by element, taking first[0,0} * np.ones((2,2)) and concatenating the results. Commented Jan 27, 2022 at 22:48

2 Answers 2

2

Just repeat twice:

>>> first.repeat(2, axis=1).repeat(2, axis=0)
array([[4, 4, 5, 5],
       [4, 4, 5, 5],
       [7, 7, 9, 9],
       [7, 7, 9, 9]])

Slightly more compact:

first.repeat(2,1).repeat(2,0)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use scipy.ndimage.zoom with the order set to 0 to keep replicating your array

>>> arr
array([[4, 5],
       [7, 9]])
>>> scipy.ndimage.zoom(arr, 2, order=0)
array([[4, 4, 5, 5],
       [4, 4, 5, 5],
       [7, 7, 9, 9],
       [7, 7, 9, 9]])

zoom also works with greater values and/or can approximate to floats (zooming in or out) and in different scales by-axis (including higher dimensions)

>>> scipy.ndimage.zoom(arr, 5, order=0)
array([[4, 4, 4, 4, 4, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 4, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 4, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 4, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 4, 5, 5, 5, 5, 5],
       [7, 7, 7, 7, 7, 9, 9, 9, 9, 9],
       [7, 7, 7, 7, 7, 9, 9, 9, 9, 9],
       [7, 7, 7, 7, 7, 9, 9, 9, 9, 9],
       [7, 7, 7, 7, 7, 9, 9, 9, 9, 9],
       [7, 7, 7, 7, 7, 9, 9, 9, 9, 9]])
>>> scipy.ndimage.zoom(arr, 0.5, order=0)
array([[4]])
>>> scipy.ndimage.zoom(arr, (2,3), order=0)
array([[4, 4, 4, 5, 5, 5],
       [4, 4, 4, 5, 5, 5],
       [7, 7, 7, 9, 9, 9],
       [7, 7, 7, 9, 9, 9]])

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.