I was just looking at the following numpy infographic.
https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Numpy_Python_Cheat_Sheet.pdf
I am wondering if there is any difference between np.copy(a)
and a.copy()
- or are they just synonyms for the same operation?
1 Answer 1
If a
is a numpy.array
, the result will be the same. But if a
is something else, a.copy()
will return the same type as a
or fail depending on its type, and np.copy(a)
will always return numpy.array
. Try, e.g. the following:
import pandas as pd
for x in (list(range(3)), np.array(range(3)), pd.Series(range(3))):
print()
print(repr(x.copy()))
print(repr(np.copy(x)))
UPD: There is another difference. Both methods have an additional order
argument defining the memory order in the copy with different default values. In np.copy
it is 'K'
, which means "Use the order as close to the original as possible", and in ndarray.copy
it is 'C'
(Use C order). E.g.
x = np.array([[1,2,3],[4,5,6]], order='F')
for y in [x, np.copy(x), x.copy()]:
print(y.flags['C_CONTIGUOUS'], y.flags['F_CONTIGUOUS'])
Will print
False True
False True
True False
And in both cases the copies are deep in the sense that the array data itself are copied, but shallow in the sense that in case of object arrays the objects themselves are not copied. Which can be demonstrated by
x = np.array([1, [1,2,3]])
y = x.copy()
z = np.copy(x)
y[1][1] = -2
z[1][2] = -3
print(x)
print(y)
print(z)
All the three printed lines are
[1 list([1, -2, -3])]
-
Assuming that
a
is of typenp.array
, do both methodsnp.copy(a)
anda.copy()
make deep copies?AlanSTACK– AlanSTACK2019年05月07日 18:48:52 +00:00Commented May 7, 2019 at 18:48 -
deep copy only applies to object dtype arrays. For others all copies are the same.hpaulj– hpaulj2019年05月07日 18:52:40 +00:00Commented May 7, 2019 at 18:52
-
1@AlanSTACK, they both make deep copy in the sense that the array data are copied. But if you have an object array, the objects are not copied. If you need such a deep-deep copy, use
copy.deepcopy
.aparpara– aparpara2019年05月07日 19:29:33 +00:00Commented May 7, 2019 at 19:29