Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Numpy repeating an arange array

so say I do this

x = np.arange(0, 3)

which gives

array([0, 1, 2])

but what can I do like

x = np.arange(0, 3)*repeat(N=3)times

to get

array([0, 1, 2, 0, 1, 2, 0, 1, 2])
like image 297
Runner Bean Avatar asked Dec 21 '16 02:12

Runner Bean


1 Answers

I've seen several recent questions about resize. It isn't used often, but here's one case where it does just what you want:

In [66]: np.resize(np.arange(3),3*3)
Out[66]: array([0, 1, 2, 0, 1, 2, 0, 1, 2])

There are many other ways of doing this.

In [67]: np.tile(np.arange(3),3)
Out[67]: array([0, 1, 2, 0, 1, 2, 0, 1, 2])
In [68]: (np.arange(3)+np.zeros((3,1),int)).ravel()
Out[68]: array([0, 1, 2, 0, 1, 2, 0, 1, 2])

np.repeat doesn't repeat in the way we want

In [70]: np.repeat(np.arange(3),3)
Out[70]: array([0, 0, 0, 1, 1, 1, 2, 2, 2])

but even that can be reworked (this is a bit advanced):

In [73]: np.repeat(np.arange(3),3).reshape(3,3,order='F').ravel()
Out[73]: array([0, 1, 2, 0, 1, 2, 0, 1, 2])
like image 132
hpaulj Avatar answered Sep 26 '22 00:09

hpaulj