2
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]

martineau
  • 119,623
  • 25
  • 170
  • 301
Pkzzz
  • 101
  • 1
  • 7
  • The CSV data shoud be: 0.15098,0,10.01,0,0.547,6.021,82.6,2.7474,6,432,17.8,394.51,10.3,19.2 12.048,0,18.1,0,0.614,5.648,87.6,1.9512,24,666,20.2,291.55,14.1,20.8 – Pkzzz Apr 08 '20 at 23:32
  • 1
    See [my answer](https://stackoverflow.com/a/11350095/355230) to a different CSV-related question. – martineau Apr 08 '20 at 23:54

1 Answers1

1

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))
Björn
  • 1,610
  • 2
  • 17
  • 37
  • The output of y is still empty in this way, the x is correct. – Pkzzz Apr 08 '20 at 23:44
  • I found an interesting thing, if I delete x.append([row[:13] for row in fl]), the output y is correct – Pkzzz Apr 08 '20 at 23:53
  • Thank you, btw can I format the output to two brackets rather than three? I would like to get [['19.2']], [['20.8']] but now it is [[['19.2']], [['20.8']]] – Pkzzz Apr 09 '20 at 00:19