1

How can I replicate numpy array, so that it would be repeated (as a whole array) n times?

So with an example array:

import numpy as np
x = np.arange(0, 5)

I want to create an array like below, without a need of manually typing np.arange(0, 5) n times:

x_3times = np.concatenate([np.arange(0, 5), np.arange(0, 5), np.arange(0, 5)])     

or with a set length of output (e.g. 12)?

x_12 = np.concatenate([np.arange(0, 5), np.arange(0, 5), np.arange(0, 5)])[0:12]  

2 Answers 2

3

You can use np.tile.

>> x_3times = np.tile(x, 3)
>> x_3times

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

For repeating till some particular limit, use np.resize

>> x_12 = np.resize(x, 12)
>> x_12

array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I have edited the question for some extension - is there any method for that? (other than slicing) after np.tile
2

Simply try list comprehension:

x_3times = np.concatenate([np.arange(0, 5) for x in range(3)])

where the number 3 can be substituted by any number n.

edit

if you want to limit the length by any number, you can simply do:

cutoff = 12
x_3times = np.concatenate([np.arange(0, 5) for x in range(3)])[:cutoff]

which will result to:

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

However, this isn't a very efficient line of code, especially when dealing with large numbers. Another answer would probably be to make a generator:

def generator(arr, n, cutoff=None):
    length = len(arr)
    if cutoff:
        for i in range(cutoff):
            yield arr[i%length]
    else:
        for _ in range(n):
            for i in arr:
                yield i

array = np.array([x for x in generator(np.arange(0, 5), 3, 12)])

1 Comment

Thanks! I have edited the question for some extension - is there any method for that? (other than slicing) after creating x_3times

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.