yatu
yatu

Reputation: 88236

Repeat values from a sequence up to n

Say I want to repeat a sequence of consecutive 0s and 1s up to n. One way I can think of is:

seq = np.array([0,1])
a = np.tile(seq, math.ceil(n/2))[:n]

Where I use math.ceil(n/2) so that only an extra number is generated in the case of having an odd n. But is there a more concise way of doing this? This should ideally be extendable to any given sequence, for example:

n = 6
seq = np.array([1,2,3,4])
np.tile(seq, math.ceil(n/2))[:n]
array([1, 2, 3, 4, 1, 2])

Upvotes: 0

Views: 53

Answers (1)

hpaulj
hpaulj

Reputation: 231355

np.resize may work for you.

In [43]: seq = np.array([1,2,3,4])
In [44]: np.resize(seq, 6)
Out[44]: array([1, 2, 3, 4, 1, 2])

We don't use resize (function or method) that often, but in this case the fill pattern for the function version meets your needs.

Upvotes: 1

Related Questions