P.J. P.J. - 3 months ago 9
Python Question

Adding a column header to a csv in python

I have a csv that contains just 1 column of domain names that range from about 300 to 1500 lines, looking similar to the following:

google.com
abc.net
yahoo.com
cnn.com
twitter.com


All I need to do is add a column header of "domain" so my csv will look like:

domain
google.com
abc.net
yahoo.com
cnn.com
twitter.com


I attempted the following using pandas:

from pandas import read_csv
x = read_csv('domains.csv')
x.columns = ['domain']
x.to_csv('out.csv')


This results in a csv with the added column header, but it also added an additional column with the row numbers, which I don't want... what am I doing wrong?

domain
0 google.com
1 abc.net
2 yahoo.com
3 cnn.com
4 twitter.com

Answer

you need to set index=False when writing to_csv to remove the additional column:

x.to_csv('out.csv',index=False)
Comments