How To Copy Pandas DataFrame?

Table Of Contents:

  1. Syntax To Copy A Data Frame.
  2. Examples Of Copying A DataFrame.

(1) Syntax:

DataFrame.copy(deep=True)

Description:

  • Make a copy of this object’s indices and data.

  • 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 (see notes below).
  • 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).

Parameters:

  1. deep: bool, default 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.

Returns:

  1. copy: Series or DataFrame: Object type matches caller.

(2) Examples Of Copying:

Example-1

import pandas as pd
student = {'Name':['Subrat','Abhispa','Arpita','Anuradha','Namita'],
          'Roll_No':[100,101,102,103,104],
          'Subject':['Math','English','Science','History','Commerce'],
          'Mark':[95,88,76,73,93]}
student_object1 = pd.DataFrame(student)
student_object1

Output:

Copying The Object With (=) Operator:

student_object2 = student_object1
student_object2

Output:

Changing The Second Object:

student_object2['Name'][0] = 'Monika'
student_object1

Output:

student_object2

Output:

Note:

  • Here you can see that if you change the second DataFrame the first one is also getting changed.
  • This is the problem with (=) equals to operator while copying.

Example-2

import pandas as pd
student = {'Name':['Subrat','Abhispa','Arpita','Anuradha','Namita'],
          'Roll_No':[100,101,102,103,104],
          'Subject':['Math','English','Science','History','Commerce'],
          'Mark':[95,88,76,73,93]}
student_object1 = pd.DataFrame(student)
student_object1

Output:

Copying The Object Copy() Method:

student_object2 = student_object1.copy()
student_object2

Output:

Changing The Second Object:

student_object2['Name'][0] = 'Monika'
student_object1

Output:

student_object2

Output:

Note:

  • Here you can see that if you change the second object, it won’t change the first one.

Leave a Reply

Your email address will not be published. Required fields are marked *