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.
@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
:So, this accomplishes repeating along one axis, to get it along multiple axes (as you might want), simply nest the
np.repeat
calls: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:
Here when the second argument is a
list
it specifies a row-wise (rows in this case becauseaxis=0
) repeats for each row.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:
(dtlussier's solution is better)