1

I'm new in python programming and i have a question about reading from csv file. What am I trying to do is to split in 2 my csv file and save in two list. So form my next csv file:

    5.1,3.5,1.5,0.2,setosa
    4.9,3.0,1.4,0.2,setosa
    4.6,3.1,1.5,0.2,setosa

I need my lists to look like:

firstList = [ [5.1, 3.5, 1.5, 0.2], [4.9, 3.0, 1.4, 0.2], [4.6, 3.1, 1.5, 0.2] ]
secondList = ['setosa', 'setosa', 'setosa']

I tried different time, but my closest result is the next one:

firstList = []
secondList = []

with open('file.csv') as file:
    fileReader = csv.reader(file, delimiter=',')
    for row in fileReader:
        firstList.append(row)
        secondList.append(row[4])

And the output for this one is:

firstList = [ ['5.1', '3.5', '1.5', '0.2', 'setosa'], ['4.9', '3.0', '1.4', '0.2', 'setosa'], ['4.6', '3.1', '1.5', '0.2', 'setosa'] ]
secondList = ['setosa', 'setosa', 'setosa']

I just want to get rid of string 'setosa' from my firstList and also convert everything else into int Any help would be grateful. Thank you!

1 Answer 1

1

You can build a sublist of the first three cells in the row then build floats as you create a new list from them.

firstList = []
secondList = []

with open('file.csv') as file:
    fileReader = csv.reader(file, delimiter=',')
    for row in fileReader:
        firstList.append([float(cell) for cell in row[:3]])
        secondList.append(row[4])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.