How does the series.copy() method work in Pandas?

PandasServer Side ProgrammingProgramming

The pandas.Series.copy() method is used to create a copy of a series object’s indices and its data (values). And it returns a copied series object as a result.

The copy() method has one parameter which is “deep”. The default value for this deep parameter is True. When the input of the deep parameter is “True”, it means the copy method makes a deep copy of the given series indices and data also.

If the input for the deep parameter is “False”, then it means the copy method creates an object without copying the data and the indices of the given series object (it only copies the references of both data and indices).

Example 1

import pandas as pd

index = list("WXYZ")

#create a pandas Series
series = pd.Series([98,23,43,45], index=index)

print(series)

# create a copy
copy_sr = series.copy()

print("Copied series object:",copy_sr)

# update a value
copy_sr['W'] = 55

print("objects after updating a value: ")
print(copy_sr)

print(series)

Explanation

Initially, we have created a pandas Series using a list of integer values with labeled indexes “W, X, Y, Z”. After that created a copied series object with the default value of deep parameter (“True”).

Output

W 98
X 23
Y 43
Z 45
dtype: int64

Copied series object:
W 98
X 23
Y 43
Z 45
dtype: int64

objects after updating a value:
W 55
X 23
Y 43
Z 45

dtype: int64
W 98
X 23
Y 43
Z 45
dtype: int64

In the above output block, we can see the initial series object and copied object. After creating a copy, we have updated a value “55” in the copied object at index position “W”. The changes we made in the copied Series object do not affect the original Series.

Example 2

import pandas as pd

index = list("WXYZ")

#create a pandas Series
series = pd.Series([98,23,43,45], index=index)

print(series)

# create a copy
copy_sr = series.copy(deep=False)

print("Copied series object:",copy_sr)

copy_sr['W'] = 55

print("objects after updating a value: ")
print(copy_sr)

print(series)

Explanation

In this example, we change the default value of the deep parameter from True to False. So, the copy method copies the Series object with reference id of indices and data.

If we make any changes to any of the Series objects, those changes will reflect on the other series object also.

Output

W 98
X 23
Y 43
Z 45
dtype: int64

Copied series object: W 98
X 23
Y 43
Z 45
dtype: int64

objects after updating a value:
W 55
X 23
Y 43
Z 45
dtype: int64

W 55
X 23
Y 43
Z 45
dtype: int64

After creating the copy. We updated the value “55” at index position “W” for the copied series only, but the changes are also updated in the original series. We can see the differences in the above output block.

raja
Updated on 09-Mar-2022 07:41:39

Advertisements