How to get rid of 'Unnamed: 0' column in a pandas DataFrame read in from CSV file?

Solution for the situations when an Unnamed: 0 column in pandas comes when you are reading CSV file. By Pranit Sharma Last updated : September 20, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consists of rows, columns, and the data.

DataFrame can be created with the help of Python dictionaries or lists but in the real world, CSV files are imported and then converted into DataFrames. Sometimes, DataFrames are first written into CSV files. Here, we are going to write a DataFrame into a CSV file.

'Unnamed: 0' column in a pandas DataFrame read in from CSV file

Sometimes, while reading a CSV file, we get an unnamed column which is in the form of 'Unnamed: 0'. We do not need this unwanted column hence we need to drop this column. Here, we are going to learn how to get rid of this unwanted column?

Let us understand with the help of an example,

Example to demonstrate the 'Unnamed: 0' column

# Importing pandas package
import pandas as pd

# Importing dataset
data=pd.read_csv('C:/Users/hp/Desktop/Includehelp/mycsv1.csv')

# Print the dataset
print(data)

Output

The output of the above program is:

Example 1: get rid of 'Unnamed: 0' column

Solution for the situations when an Unnamed: 0 column in pandas comes

Here, we can observe the red arrow shows that we have an unwanted column named 'unnamed:0', now we need to pass index_col=[0] which will drop this unwanted column.

# Importing Pandas package
import pandas as pd

# Importing dataset
data=pd.read_csv('C:/Users/hp/Desktop/Includehelp/mycsv1.csv', index_col=[0])

# Print the dataset
print(data)

Output

The output of the above program is:

Example 2: get rid of 'Unnamed: 0' column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.