Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a column header to a csv in python

Tags:

python

pandas

csv

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
like image 932
P.J. Avatar asked Jan 21 '26 19:01

P.J.


1 Answers

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

x.to_csv('out.csv',index=False)
like image 197
shivsn Avatar answered Jan 23 '26 09:01

shivsn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!