Pandas to_csv call is prepending a comma

Set index=False (the default is True hence why you see this output) so that it doesn’t save the index values to your csv, see the docs

So this:

df = pd.DataFrame({'a':np.arange(5), 'b':np.arange(5)})
df.to_csv(r'c:\data\t.csv')

results in

,a,b
0,0,0
1,1,1
2,2,2
3,3,3
4,4,4

Whilst this:

df.to_csv(r'c:\data\t.csv', index=False)

results in this:

a,b
0,0
1,1
2,2
3,3
4,4

It’s for the situation where you may have some index values you want to save

Leave a Comment