numpy.ndarray.copy — NumPy v2.6.dev0 Manual

Learn | NEPs | User Guide | API reference | Building from source | Development | Release notes | NumPy’s module structure | Array objects | The N-dimensional array (ndarray) | Scalars | Data type objects (dtype) | Data type promotion in NumPy | Iterating over arrays | Standard array subclasses | Masked arrays | The array interface protocol | Datetimes and timedeltas | Universal functions (ufunc) | Routines and objects by topic | Typing (numpy.typing) | NumPy C-API | Array API standard compatibility | CPU/SIMD optimizations | Thread Safety | Global Configuration Options | NumPy security | Testing guidelines

method

ndarray.copy(order='C')

#

Return a copy of the array.

Parameters:order{‘C’, ‘F’, ‘A’, ‘K’}, optionalControls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and

numpy.copy

are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)

Notes

This function is the preferred method for creating an array copy. The function

numpy.copy

is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.

Examples

>>> importnumpyasnp>>> x=np.array([[1,2,3],[4,5,6]],order='F')>>> y=x.copy()>>> x.fill(0)>>> xarray([[0, 0, 0], [0, 0, 0]])>>> yarray([[1, 2, 3], [4, 5, 6]])>>> y.flags['C_CONTIGUOUS']TrueFor arrays containing Python objects (e.g. dtype=np.object_), the copy is a shallow one. The new array will contain the same object which may lead to surprises if that object can be modified (is mutable):

>>> a=np.array([1,'m',[2,3,4]],dtype=np.object_)>>> b=a.copy()>>> b[2][0]=10>>> aarray([1, 'm', list([10, 3, 4])], dtype=object)To ensure all elements within an object array are copied, use

copy.deepcopy

:

>>> importcopy>>> a=np.array([1,'m',[2,3,4]],dtype=np.object_)>>> c=copy.deepcopy(a)>>> c[2][0]=10>>> carray([1, 'm', list([10, 3, 4])], dtype=object)>>> aarray([1, 'm', list([2, 3, 4])], dtype=object)

1 1