repeat a numpy array x number of times

Viewed 1735

So lets say I have a numpy array that looks like this:

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

and another variable that says the number of times I want it repeated, like 3.

My desired result would be: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

I know I could use a loop and np.concatenate() to achieve this, but I'm working with very large arrays, and was hoping for a more efficient way to do this because it seems to me that np.concatenate with a loop would take quite a long time if I have a large array and need it duplicated a large number of times (this would result in a lot of expensive copies). Is there a more efficient way to do this?

2 Answers

This should clarify:

import numpy as np

lst = [1, 2, 3, 4]
four_list = 4 * lst
print(four_list)

np_arr = np.array(lst)
np_multiplied_arr = 4 * np_arr
print(np_multiplied_arr)

np_four_arr = np.tile(np_arr, 4)
print(np_four_arr)

Result:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
[ 4  8 12 16]
[1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4]

Note how the code that works to repeat (or tile) a list in Python doesn't work as expected in Numpy, but there is the .tile() operation to help out.

It may not be the best solution but you can do this:

import numpy as np
# Our list
my_list = [1, 2, 3]
# How many times we want to repeat the list
times_to_repeat = 3
# Our final numpy array
my_numpy_array = np.array(my_list*times_to_repeat)

Thats what we will get:

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

But if your input is in numpy array you can do it like that:

import numpy as np
# Our list
my_list = list(np.array([1, 2, 3]))
# How many times we want to repeat the list
times_to_repeat = 3
# Our final numpy array
my_numpy_array = np.array(my_list*times_to_repeat)

The output will be the same as above, its a simple workaround

Related