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
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)
Comments
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.
1 Comment
dkv
But, does importing
copy have any side-effects beyond the extra line of code?
import copyto usecopy.copy.copyjust delegates the action to the objects own copy method, where possible. In fact you can read thecopy.copycode yourself.arr.__copy__is a method.np.copyis also python code.arr.copy()most often.deepcopyhas an addedmemoparameter, which is discussed at Python: Numpy deepcopy TypeError