Currently, I have some code like this
import numpy as np
ret = np.array([])
for i in range(100000):
tmp = get_input(i)
ret = np.append(ret, np.zeros(len(tmp)))
ret = np.append(ret, np.ones(fixed_length))
I think this code is not efficient as np.append needs to return a copy of the array instead of modify the ret in-place
I was wondering whether I can use the extend for a numpy array like this:
import numpy as np
from somewhere import np_extend
ret = np.array([])
for i in range(100000):
tmp = get_input(i)
np_extend(ret, np.zeros(len(tmp)))
np_extend(ret, np.ones(fixed_length))
So that the extend would be much more efficient.
Does anyone have ideas about this?
Thanks!
Imagine a numpy array as occupying one contiguous block of memory. Now imagine other objects, say other numpy arrays, which are occupying the memory just to the left and right of our numpy array. There would be no room to append to or extend our numpy array. The underlying data in a numpy array always occupies a contiguous block of memory.
So any request to append to or extend our numpy array can only be satisfied by allocating a whole new larger block of memory, copying the old data into the new block and then appending or extending.
So: