Copy DataFrame in Pandas

Copy DataFrame in Python

💡 Outline
You can copy DataFrame in Pandas using copy() method of DataFrame. By default, it will create deep copy of DataFrame.

Output:

As visible in the output, the changes we made to the df1 DataFrame are reflected in the original df DataFrame. To create copies of a DataFrame, we can use the copy() function provided by the pandas module.

We have two different copies available in Python. A shallow copy and a deep copy.

A shallow copy creates a reference to the original object. Any changes made to this copy are affected in the original object as well.

However, a deep copy recursively adds all the data of the original object to a new object. This way any changes made in the deep copy are not reflected in the original copy.

## Using copy() method to deep copy DataFrame in Pandas
By default, the copy function creates a deep copy. It has a deep parameter, which is set to True by default.

For example,

Output:

In the above example, a deep copy of the original DataFrame was created. Changes made to this copy are not reflected in the original.

## Using copy() method to shallow copy DataFrame in Pandas
If we set the deep parameter as false, a shallow copy is created.

See the following code.

Output:

We can also use the earlier discussed assignment operator = to create shallow copies of DataFrames.

That’s all about how to copy DataFrame in Pandas.

Was this post helpful?

Leave a Reply

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