How to read CSV file specified column without using pandas?

Viewed 102
def loadData(fileName):
    x = []
    y = []
    fl = csv.reader(open(fileName,'r'))
    x = list(fl)
    y.append([row[13] for row in fl])
    return x, y 

I use this but got y is empty, my csv data is enter image description here

I want got x is all the rows, and y output [19.2, 20.8]

1 Answers

You need to iterate over the rows in csv file, as you did for y: x.append()

The complete code should look something like this:

def loadData(fileName):
    x = []
    y = []
    fl = csv.reader(open(fileName,'r'))
    for row in fl:
        y.append([row[-1:])
        x.append([row[:-1])
    return x, y 

This gives you a list of lists for x. I am not sure what you expect the output to look like however if you just want a flat list you can use a flatten lambda function (source see here):

flatten = lambda l: [item for sublist in l for item in sublist]
x = flatten(x)

Please note that its recommend to use with-Syntax for file readers
An Example for the CSV Reader from the docs:

with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Related