I have a situation wherein sometimes when I read a csv
from df
I get an unwanted index-like column named unnamed:0
.
file.csv
JavaScript
x
5
1
,A,B,C
2
0,1,2,3
3
1,4,5,6
4
2,7,8,9
5
The CSV is read with this:
JavaScript
1
7
1
pd.read_csv('file.csv')
2
3
Unnamed: 0 A B C
4
0 0 1 2 3
5
1 1 4 5 6
6
2 2 7 8 9
7
This is very annoying! Does anyone have an idea on how to get rid of this?
Advertisement
Answer
It’s the index column, pass pd.to_csv(..., index=False)
to not write out an unnamed index column in the first place, see the to_csv()
docs.
Example:
JavaScript
1
12
12
1
In [37]:
2
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
3
pd.read_csv(io.StringIO(df.to_csv()))
4
5
Out[37]:
6
Unnamed: 0 a b c
7
0 0 0.109066 -1.112704 -0.545209
8
1 1 0.447114 1.525341 0.317252
9
2 2 0.507495 0.137863 0.886283
10
3 3 1.452867 1.888363 1.168101
11
4 4 0.901371 -0.704805 0.088335
12
compare with:
JavaScript
1
11
11
1
In [38]:
2
pd.read_csv(io.StringIO(df.to_csv(index=False)))
3
4
Out[38]:
5
a b c
6
0 0.109066 -1.112704 -0.545209
7
1 0.447114 1.525341 0.317252
8
2 0.507495 0.137863 0.886283
9
3 1.452867 1.888363 1.168101
10
4 0.901371 -0.704805 0.088335
11
You could also optionally tell read_csv
that the first column is the index column by passing index_col=0
:
JavaScript
1
11
11
1
In [40]:
2
pd.read_csv(io.StringIO(df.to_csv()), index_col=0)
3
4
Out[40]:
5
a b c
6
0 0.109066 -1.112704 -0.545209
7
1 0.447114 1.525341 0.317252
8
2 0.507495 0.137863 0.886283
9
3 1.452867 1.888363 1.168101
10
4 0.901371 -0.704805 0.088335
11