5

Is there any situation where I would want to use NumPy's np.copy() over Python's copy.copy() method? As far as I can tell, both create shallow copies, but NumPy is limited to arrays. Is there any performance or special handling by NumPy that's not accounted for by copy?

asked May 10, 2018 at 22:56
4
  • For starters, the implementation would differ. Furthermore, you don't have to import copy to use copy. Commented May 10, 2018 at 22:59
  • 1
    We can double check this, but I think copy.copy just delegates the action to the objects own copy method, where possible. In fact you can read the copy.copy code yourself. arr.__copy__ is a method. np.copy is also python code. Commented May 11, 2018 at 1:05
  • 1
    I see and use arr.copy() most often. Commented May 11, 2018 at 1:10
  • deepcopy has an added memo parameter, which is discussed at Python: Numpy deepcopy TypeError Commented May 11, 2018 at 1:25

2 Answers 2

3

Yes, there are side effects and numpy code is around 20% faster than pure python for float64 types.

In [1]: import numpy as np
In [2]: from copy import copy
In [3]: arr = np.random.rand(10000, 10000)
In [4]: %timeit copy(arr)
535 ms ± 97.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [5]: %timeit np.copy(arr)
453 ms ± 19.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [6]: %timeit arr.copy()
456 ms ± 22 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
answered Nov 27, 2020 at 13:34
2

numpy.copy allows more control over the memory layout of the result with the order argument, and it always produces an array, even if given some other array-like. Also, you don't have to separately import the copy module.

answered May 10, 2018 at 22:58
1
  • But, does importing copy have any side-effects beyond the extra line of code? Commented May 10, 2018 at 23:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.