Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing and stretching a NumPy array

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.

like image 955
Matthew Avatar asked Nov 19 '10 15:11

Matthew


People also ask

Can you resize a NumPy array?

With the help of Numpy numpy. resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more.

How do I expand an array in NumPy?

To expand the shape of an array, use the numpy. expand_dims() method. Insert a new axis that will appear at the axis position in the expanded array shape. The function returns the View of the input array with the number of dimensions increased.

What is the difference between reshape and resize in NumPy?

reshape() and numpy. resize() methods are used to change the size of a NumPy array. The difference between them is that the reshape() does not changes the original array but only returns the changed array, whereas the resize() method returns nothing and directly changes the original array.


2 Answers

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

like image 72
dtlussier Avatar answered Sep 25 '22 12:09

dtlussier


>>> 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]]) 
like image 45
kennytm Avatar answered Sep 23 '22 12:09

kennytm