连接 Numpy 数组而不复制 [英] Concatenate Numpy arrays without copying
问题描述
在 Numpy 中,我可以使用 np.append
或 np.concatenate
端到端连接两个数组:
但是这些复制了它们的输入数组:
<预><代码>>>>Z[0,:] = 0>>>Z数组([[ 0, 0, 0],[-1, -2, -3],[ 4, 5, 6]])>>>X数组([[1, 2, 3]])有没有办法将两个数组连接成一个视图,即无需复制?这需要 np.ndarray
子类吗?
属于 Numpy 数组的内存必须是连续的.如果单独分配数组,它们在内存中是随机分散的,没有办法将它们表示为视图Numpy数组.
如果你事先知道你需要多少个数组,你可以从你预先分配的一个大数组开始,让每个小数组成为大数组的一个视图(例如通过切片获得).
In Numpy, I can concatenate two arrays end-to-end with np.append
or np.concatenate
:
>>> X = np.array([[1,2,3]])
>>> Y = np.array([[-1,-2,-3],[4,5,6]])
>>> Z = np.append(X, Y, axis=0)
>>> Z
array([[ 1, 2, 3],
[-1, -2, -3],
[ 4, 5, 6]])
But these make copies of their input arrays:
>>> Z[0,:] = 0
>>> Z
array([[ 0, 0, 0],
[-1, -2, -3],
[ 4, 5, 6]])
>>> X
array([[1, 2, 3]])
Is there a way to concatenate two arrays into a view, i.e. without copying? Would that require an np.ndarray
subclass?
The memory belonging to a Numpy array must be contiguous. If you allocated the arrays separately, they are randomly scattered in memory, and there is no way to represent them as a view Numpy array.
If you know beforehand how many arrays you need, you can instead start with one big array that you allocate beforehand, and have each of the small arrays be a view to the big array (e.g. obtained by slicing).
这篇关于连接 Numpy 数组而不复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!