Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python csv without header

Tags:

With header information in csv file, city can be grabbed as:

city = row['city'] 

Now how to assume that csv file does not have headers, there is only 1 column, and column is city.

like image 825
bobsr Avatar asked Aug 02 '10 11:08

bobsr


People also ask

How do I read a CSV file without header in Python?

To read CSV file without header, use the header parameter and set it to “None” in the read_csv() method.

How do I save a CSV file without the header?

To write DataFrame to CSV without column header (remove column names) use header=False param on to_csv() method.


2 Answers

You can still use your line, if you declare the headers yourself, since you know it:

with open('data.csv') as f:     cf = csv.DictReader(f, fieldnames=['city'])     for row in cf:         print row['city'] 

For more information check csv.DictReader info in the docs.

Another option is to just use positional indexing, since you know there's only one column:

with open('data.csv') as f:     cf = csv.reader(f)     for row in cf:         print row[0] 
like image 126
nosklo Avatar answered Feb 13 '23 23:02

nosklo


You can use pandas.read_csv() function similarly to the way @nosklo describes, as follows:

df = pandas.read_csv("A2", header=None) print df[0] 

or

df = pandas.read_csv("A2", header=None, names=(['city'])) print df['city'] 
like image 27
Marat Avatar answered Feb 13 '23 22:02

Marat