3

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?

asked May 7, 2019 at 18:17

1 Answer 1

7

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])]
answered May 7, 2019 at 18:37
3
  • Assuming that a is of type np.array, do both methods np.copy(a) and a.copy() make deep copies? Commented May 7, 2019 at 18:48
  • deep copy only applies to object dtype arrays. For others all copies are the same. Commented 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. Commented May 7, 2019 at 19:29

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.