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
相关推荐
AI探索者4 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者4 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh5 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅5 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽6 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时10 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿12 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python