Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
s = pd.Series([2, 3], index=["p", "q"])
s
Out[2]:
p    2
q    3
dtype: int64
In [3]:
s_copy = s.copy()
s_copy
Out[3]:
p    2
q    3
dtype: int64

Shallow copy versus default (deep) copy:

In [4]:
s = pd.Series([2, 3], index=["p", "q"])
deep = s.copy()
shallow = s.copy(deep=False)

Shallow copy shares data and index with original.

In [5]:
s is shallow
Out[5]:
False
In [6]:
s.values is shallow.values and s.index is shallow.index
Out[6]:
True

Deep copy has own copy of data and index.

In [7]:
s is deep
Out[7]:
False
In [8]:
s.values is deep.values or s.index is deep.index
Out[8]:
False

Updates to the data shared by shallow copy and original is reflected in both;
deep copy remains unchanged:

In [9]:
s[0] = 4
shallow[1] = 5
s
Out[9]:
p    4
q    5
dtype: int64
In [10]:
shallow
Out[10]:
p    4
q    5
dtype: int64
In [11]:
deep
Out[11]:
p    2
q    3
dtype: int64

Note that when copying an object containing Python objects, a deep copy will copy the data,
but will not do so recursively. Updating a nested data object will be reflected in the deep copy.

In [12]:
s = pd.Series([[2, 3], [4, 5]])
deep = s.copy()
s[0][0] = 8
s
Out[12]:
0    [8, 3]
1    [4, 5]
dtype: object
In [13]:
deep
Out[13]:
0    [8, 3]
1    [4, 5]
dtype: object