The copy()
method in Pandas is used to create a separate copy of a DataFrame or Series.
Example
import pandas as pd
# original DataFrame
data = {'A': [1, 2, 3],
'B': [4, 5, 6]}
df = pd.DataFrame(data)
# creating a copy of the DataFrame
df_copy = df.copy()
print(df_copy)
'''
Output
A B
0 1 4
1 2 5
2 3 6
'''
copy() Syntax
The syntax of the copy()
method in Pandas is:
df.copy(deep=True)
copy() Argument
The copy()
method takes the following argument:
deep
(optional): specifies whether to make a deep copy or a shallow copy
copy() Return Value
The copy()
method returns a new DataFrame or Series that is a copy of the original.
Example 1: Deep Copy
import pandas as pd
data = {'A': [1, 2, 3],
'B': [4, 5, 6]}
df = pd.DataFrame(data)
# deep copy
deep_copy_df = df.copy()
# modifying the copy
deep_copy_df.iloc[2] = [10, 20]
print("Original DataFrame:")
print(df)
print("\nDeep Copy DataFrame:")
print(deep_copy_df)
Output
Original DataFrame: A B 0 1 4 1 2 5 2 3 6 Deep Copy DataFrame: A B 0 1 4 1 2 5 2 10 20
In this example, we created a deep copy of the DataFrame and modified the copied DataFrame.
In deep copy, changes in the copied DataFrame don't affect the original DataFrame.
Example 2: Shallow Copy
import pandas as pd
data = {'A': [1, 2, 3],
'B': [4, 5, 6]}
df = pd.DataFrame(data)
# shallow copy
shallow_copy_df = df.copy(deep=False)
# modifying the copy
shallow_copy_df.iloc[2] = [10, 20]
print("Original DataFrame:")
print(df)
print("\nShallow Copy DataFrame:")
print(shallow_copy_df)
Output
Original DataFrame: A B 0 1 4 1 2 5 2 10 20 Shallow Copy DataFrame: A B 0 1 4 1 2 5 2 10 20
Here, we made a shallow copy of the original copy and modified the copied DataFrame.
In shallow copy, changes in the copied DataFrame shares the data with the original DataFrame and hence makes changes to the original DataFrame as well.