[英]Numpy array.resize() - zeros 'first'
I can use array.resize(shape)
to resize my array and have zeros added to those indices without any value. 我可以使用
array.resize(shape)
来调整我的数组的大小,并将零添加到那些没有任何值的索引。 If my array is [1,2,3,4]
and I use array.resize[5,0]
I get [1,2,3,4,0]
. 如果我的数组是
[1,2,3,4]
并且我使用array.resize[5,0]
我得到[1,2,3,4,0]
。 How can I append / pad the zeros to the front, yielding [0,1,2,3,4]
? 如何将零附加/填充到前面,产生
[0,1,2,3,4]
?
I am doing this dynamically - trying to use: 我动态地这样做 - 尝试使用:
array.resize(arrayb.shape)
I would like to avoid (at all costs) making an in-memory copy of the array. 我想避免(不惜一切代价)制作数组的内存副本。 That is to reverse the array, resize, and reverse again.
那就是反转数组,调整大小和反转。 Working with a view would be ideal.
使用视图将是理想的。
You could try working on an array with negative strides (though you can never be sure that resize may not have to make a copy): 您可以尝试使用负步幅处理数组(尽管您永远无法确定调整大小可能不必进行复制):
_a = np.empty(0) # original array
a = _a[::-1] # the array you work with...
# now instead of a, resize the original _a:
del a # You need to delete it first. Or resize will want refcheck=False, but that
# will be dangerous!
_a.resize(5)
# And update a to the new array:
a = _a[::-1]
But I would really suggest you make the array large enough if in any way possible, this does not seem very beautiful, but I think this is the only way short of copying around data. 但我真的建议你让数组足够大,如果以任何可能的方式,这似乎不是很漂亮,但我认为这是复制数据的唯一方法。 Your array will also have a negative stride, so it won't be contiguous, so if that means that some function you use on it must make copy, you are out of luck.
你的数组也会有一个负面的步幅,所以它不会是连续的,所以如果这意味着你在它上面使用的某些功能必须复制,那你就不走运了。
Also if you slice your a
or _a
you have to either make a copy
, or make sure you delete them before resizing. 此外,如果您对
a
或_a
切片,则必须copy
,或确保在调整大小之前将其删除。 While you can give refcheck=False
this seems to invalidate the data. 虽然你可以给
refcheck=False
但这似乎使数据无效。
I believe you can use slice assignment to do this. 我相信你可以使用切片分配来做到这一点。 I see no reason why
numpy
would need to make a copy for an operation like this, as long as it does the necessary checks for overlaps (though of course as others have noted, resize
may itself have to allocate a new block of memory). 我认为没有理由为什么
numpy
需要为这样的操作制作副本,只要它对重叠进行必要的检查(当然,正如其他人已经注意到的那样, resize
本身可能需要分配一个新的内存块)。 I tested this method with a very large array, and I saw no jump in memory usage. 我用一个非常大的数组测试了这个方法,我看到内存使用没有跳跃。
>>> a = numpy.arange(10)
>>> a.resize(15)
>>> a[5:] = a[:10]
>>> a[0:5] = 0
>>> a
array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
The following showed no jump in memory usage for the assignment operation: 以下显示分配操作的内存使用没有跳转:
>>> a = numpy.arange(100000000)
>>> a.resize(150000000)
>>> a[50000000:] = a[:100000000]
I don't know of a better way, and this is just a conjecture. 我不知道更好的方法,这只是一个猜想。 Let me know if it doesn't work.
如果它不起作用,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.