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"])
In [5]:
deep = s.copy()
In [6]:
shallow = s.copy(deep=False)

Shallow copy shares data and index with original.

In [7]:
s is shallow
Out[7]:
False
In [8]:
s.values is shallow.values and s.index is shallow.index
Out[8]:
True

Deep copy has own copy of data and index.

In [9]:
s is deep
Out[9]:
False
In [10]:
s.values is deep.values or s.index is deep.index
Out[10]:
False

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

In [11]:
s[0] = 4
In [12]:
shallow[1] = 5
s
Out[12]:
p    4
q    5
dtype: int64

In [13]:
shallow
Out[13]:
p    4
q    5
dtype: int64

In [14]:
deep
Out[14]:
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 [15]:
s = pd.Series([[2, 3], [4, 5]])
In [16]:
deep = s.copy()
In [18]:
s[0][0] = 10
s
Out[18]:
0    [10, 3]
1     [4, 5]
dtype: object

In [19]:
deep
Out[19]:
0    [10, 3]
1     [4, 5]
dtype: object