np.copy()是深拷贝还是浅拷贝

np.copy到底是深拷贝还是浅拷贝

  • 实验
    • [1. 拷贝矩阵](#1. 拷贝矩阵)
      • [2. 修改m的值](#2. 修改m的值)
      • [3. 修改拷贝矩阵的值](#3. 修改拷贝矩阵的值)
  • 官方文档

最近在用numpy的拷贝操作,发现网上对np.copy()究竟是深拷贝还是浅拷贝说法不一致,因此记录一下。

总结 :如果numpy array是一个简单的数组,np.copy()是深拷贝。如果numpy array内包含了对象,np.copy()是浅拷贝。
ps : arr.copy = np.copy(arr)

实验

1. 拷贝矩阵

原始矩阵m,分别用两种不同的方式拷贝。用np.copy()得到n, 用浅拷贝得到z

python 复制代码
import numpy as np
m = np.array([[0,1,2],[1,2,3],[3,4,5]])
# numpy拷贝, 等同于n = np.copy(m)
n = m.copy()
# 浅拷贝
z = m

输出:

python 复制代码
>>> m
array([[0, 1, 2],
       [1, 2, 3],
       [3, 4, 5]])
>>> n
array([[0, 1, 2],
       [1, 2, 3],
       [3, 4, 5]])
>>> z
array([[0, 1, 2],
       [1, 2, 3],
       [3, 4, 5]])

2. 修改m的值

python 复制代码
m[0][0]=-1

修改m的值后,使用np.copy的n值没有改变,浅拷贝z的值发生了改变

python 复制代码
>>> m
array([[-1,  1,  2],
       [ 1,  2,  3],
       [ 3,  4,  5]])
>>> n
array([[0, 1, 2],
       [1, 2, 3],
       [3, 4, 5]])
>>> z
array([[-1,  1,  2],
       [ 1,  2,  3],
       [ 3,  4,  5]])

3. 修改拷贝矩阵的值

修改n的值,mz值都没有改变

python 复制代码
n[0][0]=-2

>>> m
array([[-1,  1,  2],
       [ 1,  2,  3],
       [ 3,  4,  5]])
>>> n
array([[-2,  1,  2],
       [ 1,  2,  3],
       [ 3,  4,  5]])
>>> z
array([[-1,  1,  2],
       [ 1,  2,  3],
       [ 3,  4,  5]])

修改z的值,m值改变和n值不变

python 复制代码
z[0][0]=-3

array([[-3,  1,  2],
       [ 1,  2,  3],
       [ 3,  4,  5]])
>>> n
array([[-2,  1,  2],
       [ 1,  2,  3],
       [ 3,  4,  5]])
>>> z
array([[-3,  1,  2],
       [ 1,  2,  3],
       [ 3,  4,  5]])

因此np.copy从以上的例子来看是深拷贝, =是浅拷贝

官方文档

但是在 numpy官方文档中明确提到np.copy是浅拷贝。原因是如果array里的元素是一个对象时,如果对象的元素改变,原来的array的对象也会改变。也就是说numpy array中对象元素的拷贝是浅拷贝。

Note that np.copy is a shallow copy and will not copy object elements within arrays. This is mainly important for arrays containing Python objects. 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=object)
b = np.copy(a)
b[2][0] = 10
a
array([1, 'm', list([10, 3, 4])], dtype=object)

To ensure all elements within an object array are copied, use copy.deepcopy:

复制代码
import copy
a = np.array([1, 'm', [2, 3, 4]], dtype=object)
c = copy.deepcopy(a)
c[2][0] = 10
c
array([1, 'm', list([10, 3, 4])], dtype=object)
a
array([1, 'm', list([2, 3, 4])], dtype=object)

参考文档

  1. 官方文档
  2. 博客1
  3. 博客2
相关推荐
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时1 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1231 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero071 天前
Jev 与 Laya
python·语言模型