Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Pandas DataFrame Copy() Method

When we want to manipulate DataFrame by adding, deleting, or updating DataFrame without changing the DataFrame, we can copy and do the manipulation.

In this tutorial, we will learn the Python pandas DataFrame.copy() method. This method copies data of DataFrame and returns a new object. The below shows the syntax of the Python pandas DataFrame.copy() method.

Syntax

DataFrame.copy(deep=True)

Parameters

deep: It represents the bool(True or False), the default is True. Make a deep copy, including a copy of the data and the indices. With deep=False neither the indices nor the data are copied.

When deep=True (default), a new object will be created with a copy of the calling object’s data and indices. Modifications to the data or indices of the copy will not be reflected in the original object.

When deep=False, a new object will be created without copying the calling object’s data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa).

Example 1: Copy the DataFrame using DataFrame.copy() Method

Hew, create a DataFrame and copy the DataFrame using the DataFrame.copy() method.

#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f']})
print(df)
df1=df.copy()
print(df1)

Once we run the program we will get the following output.


A B
0 a d
1 b e
2 c f
A B
0 a d
1 b e
2 c f

Example 2: Copy the DataFrame using DataFrame.copy() Method

Let's understand with another example to copy dataframe.

#importing pandas as pd
import pandas as pd
colors = {'first_set':  ['Green','Blue','Red'],'second_set': ['Yellow','White','Blue']}
df = pd.DataFrame(colors)
print(df)
df1=df.copy()
print(df1)

Once we run the program we will get the following output.


first_set second_set
0 Green Yellow
1 Blue White
2 Red Blue
first_set second_set
0 Green Yellow
1 Blue White
2 Red Blue

Example 3: Copy the DataFrame using DataFrame.copy() Method with deep=False

When deep=False, DataFrame.copy() method creates a new object and any changes to the data of the original will be reflected in the shallow copy.

import pandas as pd
colors = {'first_set':  ['Green','Blue','Red'],'second_set': ['Yellow','White','Blue']}
df = pd.DataFrame(colors)
df1=df.copy(deep=False)
df1['first_set'] = df1['first_set'].replace(['Blue'],'Green')
print(df1)
print(df)

Once we run the program we will get the following output.


first_set second_set
0 Green Yellow
1 Green White
2 Red Blue
first_set second_set
0 Green Yellow
1 Green White
2 Red Blue

Conclusion

In this tutorial, we learned Python pandas DataFrame.copy() method. We learned the parameter of the DataFrame.copy() method, solved examples, and how this method copies the DataFrame with different parameters and differences of these parameters.