Friday, September 5, 2025
HomeLanguagesPython | Difference between Pandas.copy() and copying through variables

Python | Difference between Pandas.copy() and copying through variables

Pandas .copy() method is used to create a copy of a Pandas object. Variables are also used to generate copy of an object but variables are just pointer to an object and any change in new data will also change the previous data.

The following examples will show the difference between copying through variables and Pandas.copy() method.

Example #1: Copying through variables
In this example, a sample Pandas series is made and copied in a new variable. After that, some changes are made in the new data and compared with the old data.




# importing pandas module
import pandas as pd
  
# creating sample series
data = pd.Series(['a', 'b', 'c', 'd'])
  
# creating copy of series
new = data
  
# assigning new values
new[1]='Changed value'
  
# printing data
print(new)
print(data)


Output:
As shown in the output image, the changes made in new data are also reflected in the old data since the new variable was just a pointer to old one.

 
Example #2: Using Pandas.copy() method
In this example, pandas.copy() method is used to copy a data and some changes are made in the new data. The changes are then compared to old data.




# importing pandas module
import pandas as pd
  
# creating sample series
data = pd.Series(['a', 'b', 'c', 'd'])
  
# creating copy of series
new = data.copy()
  
# assigning new values
new[1]='Changed value'
  
# printing data
print(new)
print(data)


Output:
As shown in the output image, the changes in new data are independent and didn’t change anything in old one.

RELATED ARTICLES

Most Popular

Dominic
32267 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6635 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7026 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6720 POSTS0 COMMENTS