Resizing and stretching a NumPy array Resizing and stretching a NumPy array python python

Resizing and stretching a NumPy array


@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.


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


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>>> barray([[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)