Create a Pandas DataFrame copy

Use cases for code example

Use case examples on how to create a Pandas DataFrame copy

We create a Pandas DataFrame copy when we want to:

  • alter a dataset or dataframe and do not want it to impact the original dataset
  • update the data in a dataset while still keeping the original dataset

Dataset used in this example: Sydney AirBnB data

We will use a data capture of Sydney AirBnB listings

Click here to download the dataset

Walkthrough and explanation of code

Walkthrough of code

Copying a dataframe is very straightforward. In the code below, we perform the following steps:

  • load the Pandas library using import statement
  • read the example csv dataset into a Pandas dataframe (called df)
  • list the first 5 records in the dataframe with the head() statement
  • make a copy of the dataframe (we name this dataframe dfcopy)
  • list the first 5 records in the copied dataframe with the head() statement

Example code

Example Code

Load the dataset

#import the Pandas Library
import pandas as pd

#read the example CSV dataset
df = pd.read_csv('data//airbnb//sydney//tomslee_airbnb_sydney_1523_2017-07-23.csv')

#show 1st 5 records
df.head()

Create a Pandas DataFrame copy - loading source dataset

Copy the dataframe

#make a copy of the dataframe df and name it dfcopy
dfcopy = df.copy()

#show 1st 5 records of dfcopy
dfcopy.head()

Create a Pandas DataFrame copy - copying the dataframe

Was this article helpful?

Related Articles