Reputation: 5486
Suppose there is a 2-dimensional numpy
array of shape (10000, 100)
and size 1000000
. There is also a 1-dimensional list
of length 1000000
. What would be the fastest way to assign all the values in the list to the array? My solution is:
my_array = np.zeros([10000, 100])
my_list = range(1000000)
length_of_list = len(my_list)
for i in range(length_of_list):
my_array.flat[i] = my_list[i]
Is there maybe a better one?
Upvotes: 1
Views: 6402
Reputation: 12683
I thought that turning the list to an array and reshaping it then would be the fastest solution, but it turned out in my setup @M4rtini's one-liner is even faster:
In [25]: %%timeit -n 10
....: for i in range(length_of_list):
....: my_array.flat[i] = my_list[i]
....:
10 loops, best of 3: 420 ms per loop
In [26]: %timeit -n 10 my_array.flat[:] = my_list
10 loops, best of 3: 119 ms per loop
In [27]: %timeit -n 10 my_array = np.array(my_list).reshape(10000, 100)
10 loops, best of 3: 133 ms per loop
Upvotes: 3