且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Numpy 中就地扩展数组?

更新时间:2022-11-29 17:55:04

想象一个 numpy 数组占据一个连续的内存块.现在想象一下其他对象,比如其他 numpy 数组,它们占用我们 numpy 数组左右两侧的内存.将没有空间附加或扩展我们的 numpy 数组.numpy 数组中的底层数据始终占用连续块内存.

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.

因此,任何追加或扩展我们的 numpy 数组的请求只能通过分配一个全新的更大的内存块,将旧数据复制到新块中,然后追加或扩展来满足.

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.

所以:

  1. 它不会就地发生.
  2. 效率不高.