This tutorial will explore various techniques we can use to remove unnamed columns in a Pandas DataFrame.
Let us go exploring.
Sample DataFrame
In the code below, we have a sample CSV file that holds a sample DataFrame you can use to follow along with this guide.
The CSV is as shown:
1 2 3 4 5 6 | ,col1,col2,col3 0,N/A,N/A,N/A 1,N/A,N/A,N/A 2,N/A,N/A,N/A 3,N/A,N/A,N/A 4,N/A,N/A,N/A |
Start by importing pandas as shown below:
1 | import pandas as pd |
Next, load the csv file as shown in the example code below:
1 2 | df = pd.read_csv('sample.csv') df |
This should load the csv file into a DataFrame as shown below:
You will note that the DataFrame has an unnamed column.
Drop Unnamed Column Using drop() Function
To remove an unnamed column in Pandas, we can use the drop function as shown below:
1 | df.drop("Unnamed: 0", axis=1) |
The code above should remove the column “Unnamed: 0” from the DataFrame.
This should return:
Closing
This article discussed how to remove an unnamed column from a Pandas DataFrame using the drop function. Check the docs to learn more.
Happy coding!!