错误或功能:使用切片克隆一个numpy数组 [英] Bug or feature: cloning a numpy array w/ slicing
问题描述
按照David Morrissey对""中的列表的回答进行操作?'我正在运行一些性能测试,并且在使用numpy数组时遇到意外行为.我知道可以/应该克隆一个numpy数组w/
Following up to David Morrissey's answer on 'How to clone a list in python?' I was running some performance tests and hit unexpected behavior when working w/ numpy arrays. I know that a numpy array can/ should be cloned w/
clone = numpy.array(original)
或
clone = numpy.copy(original)
,但是错误地认为切片也可以解决问题.但是:
but have incorrectly assumed that slicing would do the trick too. However:
In [11]: original = numpy.arange(4)
In [12]: original
Out[12]: array([0, 1, 2, 3])
In [13]: clone = original[:]
In [14]: clone
Out[14]: array([0, 1, 2, 3])
In [15]: clone[0] = 1
In [16]: clone
Out[16]: array([1, 1, 2, 3])
In [17]: original
Out[17]: array([1, 1, 2, 3])
是否存在这种轻微不一致的充分原因,或者我应该提交错误?
Is there a good reason for this slight inconsistency or should I file a bug?
推荐答案
在numpy中,切片是原始数组上的引用或视图",因此它们不是副本.那是设计使然,而不是错误.原因是副本不如视图有用.
In numpy, slices are references or "views" on the original array, so they are not copies. That is by design, not a bug. The reason is that a copy is not as useful as a view.
这篇关于错误或功能:使用切片克隆一个numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!