pandas.DataFrame.copy() function | How to Copy from one dataframe to another

Spread the love

pandas.DataFrame.copy() function: This function 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).

Syntax: DataFrame.copy(deep=True)()

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.

copy : Series, DataFrame or Panel
Object type matches caller.


When deep=True, data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to copy.deepcopy in the Standard Library, which recursively copies object data (see examples below).

While Index objects are copied when deep=True, the underlying numpy array is not copied for performance reasons. Since Index is immutable, the underlying data can be safely shared and a copy is not needed.

import numpy as np import pandas as pd df1 = pd.DataFrame({'A': [5, 2], 'B': [4, 8]}) df2 = df1.copy() print(df2) df3 = df1.copy(deep=True) print(df3)


   A  B
0  5  4
1  2  8
   A  B
0  5  4
1  2  8





Leave a Reply

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