Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting CSV into Array in Python

I have a csv file like below. A small csv file and I have uploaded it here

enter image description here

I am trying to convert csv values into array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My expectation output like

enter image description here

My solution

results = []
with open("Solutions10.csv") as csvfile:
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats
    for row in reader: # each row is a list
        results.append(row)

but I am getting a

ValueError: could not convert string to float: ‘ [1’

>Solution :

You can do this:

with open("Solutions10.csv") as csvfile:
    result = [eval(k) for k in csvfile.readlines()]

Edit: Karl is cranky and wants you todo this:

with open("Solutions10.csv") as csvfile:
    result = []
    for line in csvfile.readlines():
        line = line.replace("[","").replace("]","")
        result.append([int(k) for k in line.split(",")]

But you’re an the programmer so you can do what you want. If you trust your input file eval is fine.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading