NumPy copy()

copy()方法返回给定对象的数组副本。

示例

import numpy as np

# create an array 
array1 = np.arange(5)

# create a copy of the original array array2 = np.copy(array1)
print(array2) # Output: [0 1 2 3 4]

copy() 语法

copy()的语法是

numpy.copy(array, order = 'K', subok = False)

copy()参数

copy()方法接受三个参数

  • array - 输入数据
  • subok(可选) - 决定当数据类型更改时,输出数组是否是子类,或者返回一个基类数组
  • order (可选) - 指定复制类中填充元素的顺序。

copy() 返回值

copy()方法返回给定输入的数组解释。


示例 1:使用 copy() 创建数组

import numpy as np

# copy an array from another array
array0 = np.arange(5)
array1 = np.copy(array0)
print('Array copied from Array: ',array1) # copy an array from a list list1 = [1, 2, 3, 4, 5]
array2 = np.copy(list1)
print('Array copied from List: ',array2) # copy an array from another array tuple1 = (1, 2, 3, 4, 5)
array1 = np.copy(tuple1)
print('Array copied from Tuple: ',array1)

输出

Array copied from Array:  [0 1 2 3 4]
Array copied from List:  [1 2 3 4 5]
Array copied from Tuple:  [1 2 3 4 5]

示例 2:使用 '=' 和 np.copy() 创建数组

我们也可以通过赋值运算符来创建数组的副本。

import numpy as np

# create an array
array0 = np.arange(5) # [0 1 2 3 4]

# copy an array using assignment operator array1 = array0
# change 1st element of new array array1[0] = -1 # print both arrays print(array0) print(array1)

输出

[-1  1  2  3  4]
[-1  1  2  3  4]

如示例所示,修改 array1 也会修改 array0,因为它们引用的是相同的基础数据。

如果您想创建 array0 的独立副本,您可以使用 np.copy() 函数显式创建深拷贝。

让我们看一个使用 np.copy() 的例子。

import numpy as np

# create an array
array0 = np.arange(5) # [0 1 2 3 4]

# copy an array using np.copy()
array1 = np.copy(array0)

# change 1st element of new array 
array1[0] = -1

# print both arrays
print(array0)
print(array1)

输出

[0 1 2 3 4]
[-1  1  2  3  4]

在 copy() 中使用 subok 参数

copy() 函数中的 subok 参数决定了副本是否应为原始数组类的子类(True)或基础 ndarrayFalse)。

让我们看一个例子。

import numpy as np

# create a subclass of ndarray
class CustomArray(np.ndarray):
    pass

# create an array using the custom subclass
arr = np.array([1, 2, 3]).view(CustomArray)

# create a copy with subclass preservation copySubclass = np.copy(arr, subok=True) # create a basic ndarray copy copyNdarray = np.copy(arr, subok=False)
print("Copy with Subclass:",copySubclass) print("Type of Subclass:",type(copySubclass)) print("Copy as ndArray:",copyNdarray) print("Type of ndArray Copy:",type(copyNdarray))

输出

Copy with Subclass: [1 2 3]
Type of Subclass: <class '__main__.CustomArray'>
Copy as ndArray: [1 2 3]
Type of ndArray Copy: <class 'numpy.ndarray'>

在 copy() 中使用可选的 order 参数

order 参数指定了填充副本的顺序。

顺序可以是

  • 'C' - 元素按行存储
  • 'F' - 元素按列存储
  • 'A' - 尝试保留原始数组的顺序,否则默认为 C 顺序。
  • 'K' - 按内存中出现的顺序复制元素,并默认使用 C 顺序。

注意order 参数仅影响复制数组的内存布局,不会更改数组的值或形状。


另请参阅

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战