Python CSV Without Header

Python csv without header

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]

CSV without unique headers to list of dicts with unique keys

This did return just the way I wanted. Just tweaked yours a small bit Happy Ahmad! HUGE THANKS!!! <3

def csv_to_list_with_dicts(csvfile):
with open(csvfile, "r") as file:

keys = file.readline().split(",")
alteredKeys = []
for eachKey in keys:
counter = 0
while(eachKey in alteredKeys):
counter += 1
eachKey = eachKey[:len(eachKey)-(0 if counter == 1 else 1)] + str(counter)
alteredKeys.append(eachKey)

list_of_issues = []
reader = csv.reader(file, delimiter=',', skipinitialspace=True)
for eachLine in reader:
eachIssue = dict()
columnIndex = 0
for eachColumn in eachLine:
if columnIndex < len(alteredKeys):
eachIssue[alteredKeys[columnIndex]] = eachColumn
columnIndex += 1
list_of_issues.append(eachIssue)
return list_of_issues

Plot diagram in Pandas from CSV without headers

I may havve missinterpreted your question but II'll do my best.

Th problem seems to be that you have to read a csv that have no header but you want to add them. I would use this code:

cols=['time', 'speed', 'something', 'else'] 
df = pd.read_csv('useful_data.csv', names=cols, header=None)

For your plot, the code you used should be fine with my correction. I would also suggest to look at matplotlib in order to do your graph.

read csv file without header lines in python

You can use itertools.islice:

import csv
import itertools

with open('1.csv') as f:
lines = itertools.islice(f, 11, None) # skip 11 lines, similar to [11:]
reader = csv.reader(lines)
for row in reader:
... Do whatever you want with row ..

Convert csv to dictionary when csv has no header

Using csv module.

Ex:

import csv
d = {}
with open(filename, "rU") as infile:
reader = csv.reader(infile)
for line in reader:
d[line[0]] = line[1:]
print(d)

Output:

{'user148': ['5', '9', '22', '8'], 'user142': ['0', '2', '1', '11'], 'user145': ['0', '0', '0', '3'], 'user151': ['2', '7', '8', '8'], 'user115': ['1', '4', '8', '6']}


Related Topics



Leave a reply



Submit