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
?
2 Answers 2
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)
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.
-
But, does importing
copy
have any side-effects beyond the extra line of code?dkv– dkv05/10/2018 23:04:36Commented May 10, 2018 at 23:04
import copy
to usecopy
.copy.copy
just delegates the action to the objects own copy method, where possible. In fact you can read thecopy.copy
code yourself.arr.__copy__
is a method.np.copy
is also python code.arr.copy()
most often.deepcopy
has an addedmemo
parameter, which is discussed at Python: Numpy deepcopy TypeError