0

I would like to create a new numpy array by repeating each item in another array by a given number of times (n). I am currently doing this with a for loop and .extend() with lists but this is not really efficient, especially for very large arrays.

Is there a more efficient way to do this?

def expandArray(array, n):
    new_array = []
    for item in array:
        new_array.extend([item] * n)
    new_array = np.array(new_array)
    return new_array


print(expandArray([1,2,3,4], 3)
[1,1,1,2,2,2,3,3,3,4,4,4]
1

2 Answers 2

1

I don't know exactly why, but this code runs faster than np.repeat for me:

def expandArray(array, n):
    return np.concatenate([array for i in range(0,n)])

I ran this little benchmark:

arr1 = np.random.rand(100000)
%timeit expandArray(arr1, 5)

1.07 ms ± 25.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

And np.repeat gives this result:

%timeit np.repeat(arr1,5)

2.45 ms ± 148 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Sign up to request clarification or add additional context in comments.

2 Comments

Your solution produces a different array [1 2 3 4 1 2 3 4 1 2 3 4]. If their orders are not required then this is a good solution.
The order is very important.
0

You can create a duplicated array with the numpy.repeat function.

array = np.array([1,2,3,4])

new_array = np.repeat(array, repeats=3, axis=None)
print(new_array)

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


new_array = np.repeat(array.reshape(-1,1).transpose(), repeats=3, axis=0).flatten()
print(new_array)

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

1 Comment

For the second part, to repeat the entire array, numpy.tile is available: new_array = np.tile(array, 3)

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.