How to extend an array in-place in Numpy?

后端 未结 4 986
南旧
南旧 2020-11-27 18:29

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         


        
4条回答
  •  温柔的废话
    2020-11-27 18:59

    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:

    1. It will not occur in-place.
    2. It will not be efficient.

提交回复
热议问题