incastle의 콩나물

list vs numpy appending 본문

python/알고리즘

list vs numpy appending

incastle 2021. 6. 9. 14:55

BUT, if you're appending in a large number of loops. It's faster to append list first and convert to array than appending NumPy arrays.

 

큰 숫자를 loop를 돌리면, list에 append한 다음에 마지막에 numpy로 바꿔주는 게 더 빠르다

In [8]: %%timeit
   ...: list_a = []
   ...: for _ in xrange(10000):
   ...:     list_a.append([1, 2, 3])
   ...: list_a = np.asarray(list_a)
   ...:
100 loops, best of 3: 5.95 ms per loop

In [9]: %%timeit
   ....: arr_a = np.empty((0, 3), int)
   ....: for _ in xrange(10000):
   ....:     arr_a = np.append(arr_a, np.array([[1,2,3]]), 0)
   ....:
10 loops, best of 3: 110 ms per loop
Comments