12

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])
kmario23
  • 57,311
  • 13
  • 161
  • 150
Runner Bean
  • 4,895
  • 12
  • 40
  • 60

3 Answers3

15

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])
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • great answer but I accepted the other answer as you are way to good at programming in python and the other guy needs some answers accepted to catch up on your exceptional stats! But thanks for the helpful answer :-) – Runner Bean Dec 21 '16 at 03:38
  • I think that `resize` is the exact answer to the original question – Alex-droid AD May 10 '19 at 15:29
  • @RunnerBean thanks for the score, but probs should've given it to hpaulj. That way other people get to know the best answer too! – AER Oct 06 '19 at 23:43
5

EDIT: Refer to hpaulj's answer. It is frankly better.

The simplest way is to convert back into a list and use:

list(np.arange(0,3))*3

Which gives:

>> [0, 1, 2, 0, 1, 2, 0, 1, 2]

Or if you want it as a numpy array:

np.array(list(np.arange(0,3))*3)

Which gives:

>> array([0, 1, 2, 0, 1, 2, 0, 1, 2])
AER
  • 1,549
  • 19
  • 37
  • I thought this way was easier than using a `for` loop. – AER Dec 21 '16 at 03:06
  • how do I repeat a different number of times? for example a = np.arange(4) => 0,1,2,3 np.magic_function(a, [4,3,2]) => 0,1,2,3,0,1,2,0,1 – PirateApp Apr 24 '18 at 13:20
5

how about this one?

arr = np.arange(3)
res = np.hstack((arr, ) * 3)

Output

array([0, 1, 2, 0, 1, 2, 0, 1, 2])

Not much overhead I would say.

kmario23
  • 57,311
  • 13
  • 161
  • 150