Numpy repeat

Numpy repeat#

Numpy has a very useful repeat function that has the effect of repeating elements to build up arrays.

import numpy as np

In the simplest case, you can repeat a single element \(n\) times. For example, to make a new array that repeats the number 3 five times:

np.repeat(3, 5)
array([3, 3, 3, 3, 3])

Of course there are other ways to do that particular task, such as:

np.zeros(5) + 3
array([3., 3., 3., 3., 3.])

However, np.repeat starts becoming more useful in slightly more complicated cases. For example, to make an array that contains four repeats of the string 'yes':

np.repeat('yes', 4)
array(['yes', 'yes', 'yes', 'yes'], dtype='<U3')

np.repeat really starts coming into its own when you want to repeat more than one element. For example, let us say that, for some reason, you wanted an array that repeated 3 five times followed by 2 five times. In that case you send the two elements you want to be repeated as the first argument, and the number of repeats as the second:

np.repeat([3, 2], 5)
array([3, 3, 3, 3, 3, 2, 2, 2, 2, 2])

You can also specify the number of repeats for each element. For example, say you wanted 10 five times and 20 eight times:

# 10 repeated 5 times followed by 20 repeated 8 times.
np.repeat([10, 20], [5, 8])
array([10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20])

Or 'yes' repeated four times followed by 'no' repeated six times:

# 'yes' repeated 4 times followed by 'no' repeated 6 times.
np.repeat(['yes', 'no'], [4, 6])
array(['yes', 'yes', 'yes', 'yes', 'no', 'no', 'no', 'no', 'no', 'no'],
      dtype='<U3')

You can specify more than two elements, and give numbers of repeats to each element:

# 'yes' repeated 2 times followed by 'no' repeated 3 times,
# followed by 'maybe' repeated 4 times.
np.repeat(['yes', 'no', 'maybe'], [2, 3, 4])
array(['yes', 'yes', 'no', 'no', 'no', 'maybe', 'maybe', 'maybe', 'maybe'],
      dtype='<U5')