Pandas Series.copy()


Pandas Series.copy() Tutorial

In this tutorial, we'll explore the Series.copy() method in Pandas, which is used to create a copy of a Pandas Series, with well detailed example programs.

The syntax of Series.copy(deep=True) is:

Series.copy(deep=True)

where

ParameterDescription
deepWhether to make a deep copy, i.e., recursively copy the data and index. Default is True.
Parameters of Series.copy() function

The Series.copy() method is useful when you want to create an independent copy of a Series to avoid modifying the original Series unintentionally.


Examples for Series.copy()

1. Create a shallow copy of a Series

In this example, we'll use Series.copy() to create a shallow copy of a Pandas Series.

We shall take a series in original_series, make a shallow copy to shallow_copy using Series.copy() function, then modify an element of the original_series. After that we shall print the original_series and shallow_copy to output.

Python Program

import pandas as pd

# Create a Series
original_series = pd.Series({'A': 10, 'B': 20, 'C': 30})

# Create a shallow copy
shallow_copy = original_series.copy()

# Print original and copied Series
print("Original Series:")
print(original_series)
print("\nShallow Copy:")
print(shallow_copy)

Output

Original Series:
A    10
B    20
C    30
dtype: int64

Shallow Copy:
A    10
B    20
C    30
dtype: int64

Since the values are primitive data types, the changes made to the original series are not reflected to the shallow copy.

Now, after making the copy to shallow_copy, let us modify the contents of original_series, and rerun the program.

Python Program

import pandas as pd

# Create a Series
original_series = pd.Series({'A': 10, 'B': 20, 'C': 30})

# Create a shallow copy
shallow_copy = original_series.copy()

# Modify the original Series
original_series['A'] = 99

# Print original and copied Series
print("Original Series:")
print(original_series)
print("\nShallow Copy:")
print(shallow_copy)

Output

Original Series:
A    99
B    20
C    30
dtype: int64

Shallow Copy:
A    10
B    20
C    30
dtype: int64

Summary

In this tutorial, we've covered the Series.copy() method in Pandas, which is useful for creating a copy of a Series, either shallow or deep, depending on the specified parameter.


Python Libraries