Increasing Numpy Array Size

τэкnoкraτ

ndarray of NumPy occupies a continous space in memory, it's not designed to be expanded continously. It's much better to size the an array to the maximum size then to increase the size in runtime.

However when an input size is not fully determined and it may be so large that finding a good value for the maximum size is difficult, we can try to minimize the number of increments.

A good heuristic is to double the size of an array when needed. Following piece of code expands a NumPy array by doubling.

``` {.sourceCode .python} arr = np.empty(shape=(1000,), dtype=[('col1', np.int), ('col2', np.float)])

... # More code lines later

arr = np.append(arr, np.empty_like(arr), axis=0) ```

Here, np.empty_like function removes the need for checking array size and type. We simply say give me a doubled array like this.



Comments !