Removing Unnamed:0 column in Pandas
Start your free 7-days trial now!
We can get an unwanted column named Unnamed:0
when creating a DataFrame from a csv file using the read_csv(~)
method.
Suppose we have the following text file called sample.csv
, which contains some comma-separated data:
,A,B,C0,3,4,51,6,7,8
To create a DataFrame without Unnamed:0
, we can pass index_col=0
to our read_csv(~)
call:
If we do not specify index_col=0
, the first column in the csv file is treated as the first column in the DataFrame and not the index. As there is no text (i.e. column name) before the first comma on the first line of the csv file, the resulting DataFrame column is given the name Unnamed:0
. By passing index_col=0
we tell Pandas that the first column in the csv file is the index for the DataFrame.
When writing Pandas DataFrame as a csv
If the csv file you are reading was generated from a Pandas DataFrame, then we can remove the index label when exporting the DataFrame as a csv:
df = pd.DataFrame({'A':[3,4],'B':[5,6]})df.to_csv('test.csv', index_label=False)
This will create the following csv file:
A,B0,3,51,4,6
Now, we can read this csv file without having to specify index_col=0
:
df = pd.read_csv('test.csv')df
A B0 3 51 4 6