Resizing and stretching a NumPy array

Question:

I am working in Python and I have a NumPy array like this:

[1,5,9]
[2,7,3]
[8,4,6]

How do I stretch it to something like the following?

[1,1,5,5,9,9]
[1,1,5,5,9,9]
[2,2,7,7,3,3]
[2,2,7,7,3,3]
[8,8,4,4,6,6]
[8,8,4,4,6,6]

These are just some example arrays, I will actually be resizing several sizes of arrays, not just these.

I’m new at this, and I just can’t seem to wrap my head around what I need to do.

Asked By: Matthew

||

Answers:

>>> a = numpy.array([[1,5,9],[2,7,3],[8,4,6]])
>>> numpy.kron(a, [[1,1],[1,1]])
array([[1, 1, 5, 5, 9, 9],
       [1, 1, 5, 5, 9, 9],
       [2, 2, 7, 7, 3, 3],
       [2, 2, 7, 7, 3, 3],
       [8, 8, 4, 4, 6, 6],
       [8, 8, 4, 4, 6, 6]])
Answered By: kennytm

@KennyTM’s answer is very slick, and really works for your case but as an alternative that might offer a bit more flexibility for expanding arrays try np.repeat:

>>> a = np.array([[1, 5, 9],
              [2, 7, 3],
              [8, 4, 6]])

>>> np.repeat(a,2, axis=1)
array([[1, 1, 5, 5, 9, 9],
       [2, 2, 7, 7, 3, 3],
       [8, 8, 4, 4, 6, 6]])

So, this accomplishes repeating along one axis, to get it along multiple axes (as you might want), simply nest the np.repeat calls:

>>> np.repeat(np.repeat(a,2, axis=0), 2, axis=1)
array([[1, 1, 5, 5, 9, 9],
       [1, 1, 5, 5, 9, 9],
       [2, 2, 7, 7, 3, 3],
       [2, 2, 7, 7, 3, 3],
       [8, 8, 4, 4, 6, 6],
       [8, 8, 4, 4, 6, 6]])

You can also vary the number of repeats for any initial row or column. For example, if you wanted two repeats of each row aside from the last row:

>>> np.repeat(a, [2,2,1], axis=0)
array([[1, 5, 9],
       [1, 5, 9],
       [2, 7, 3],
       [2, 7, 3],
       [8, 4, 6]])

Here when the second argument is a list it specifies a row-wise (rows in this case because axis=0) repeats for each row.

Answered By: dtlussier

Unfortunately numpy does not allow fractional steps (as far as I am aware). Here is a workaround. It’s not as clever as Kenny’s solution, but it makes use of traditional indexing:

>>> a = numpy.array([[1,5,9],[2,7,3],[8,4,6]])
>>> step = .5
>>> xstop, ystop = a.shape
>>> x = numpy.arange(0,xstop,step).astype(int)
>>> y = numpy.arange(0,ystop,step).astype(int)
>>> mg = numpy.meshgrid(x,y)
>>> b = a[mg].T
>>> b
array([[1, 1, 5, 5, 9, 9],
       [1, 1, 5, 5, 9, 9],
       [2, 2, 7, 7, 3, 3],
       [2, 2, 7, 7, 3, 3],
       [8, 8, 4, 4, 6, 6],
       [8, 8, 4, 4, 6, 6]])

(dtlussier’s solution is better)

Answered By: Paul
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.