The copy
method is used to make a copy of the given DataFrame. There are two ways a DataFrame is copied:
The method’s default behavior is the deep copy. Set the parameter deep
to False
to enable shallow copy.
Note: Refer to What is pandas in Python? to learn more about pandas.
DataFrame.copy(deep=True)
deep
is a boolean parameter that indicates whether to make a deep or a shallow copy. If True
, a deep copy is made. Otherwise, a shallow copy is made.
Let’s look at the code below:
import pandas as pddata = [['dom', 10], ['abhi', 15], ['celeste', 14]]df = pd.DataFrame(data, columns = ['Name', 'Age'])df_deep_copy = df.copy(deep=True)print("Original Dataframe - \n")print(df)print("Deep Copy Dataframe - \n")print(df_deep_copy)print("\n")print("Changing value in original dataframe\n")df.iloc[0,1] = -9print("Original Dataframe after changes - \n")print(df)print("Deep Copy Dataframe after changes - \n")print(df_deep_copy)
pandas
module.df
.df
called df_deep_copy
using the copy
method with deep
argument as True
.df
and df_deep_copy
.Age
column for one of the rows in df
.df
and df_deep_copy
.In the above code, when we modify the original dataframe, it doesn’t affect the copy of the dataframe.
Let’s look at the code below:
import pandas as pddata = [['dom', 10], ['abhi', 15], ['celeste', 14]]df = pd.DataFrame(data, columns = ['Name', 'Age'])df_shallow_copy = df.copy(deep=False)print("Original Dataframe - \n")print(df)print("Shallow Copy Dataframe - \n")print(df_shallow_copy)print("\n")print("Changing value in original dataframe\n")df.iloc[0,1] = -9print("Original Dataframe after changes - \n")print(df)print("Shallow Copy Dataframe after changes - \n")print(df_shallow_copy)
pandas
module.df
.df
called df_shallow_copy
using the copy
method with deep
argument as True
.df
and df_shallow_copy
.Age
column for one of the rows in df
.df
and df_shallow_copy
.In the above code, when we modify the original dataframe, it reflects the changes in the copy of the dataframe.