Search code examples
pythonpandascsvtypeconverter

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.

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 the programmer so you can do what you want. If you trust your input file eval is fine.