Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

python - Bug or feature: cloning a numpy array w/ slicing

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)

or

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...