简体   繁体   中英

How to fix this error: Could not convert string to float error with csv file

I am using a csv file and trying to take information to make a graph. Everything looks right until I try to plot the scatter plot and it gives me the error that it couldn't convert string to float.

   matrix=[]
     doors= []
     import csv
     with open('9car.data.csv') as csvfile: 
         M=csv.reader(csvfile, delimiter=',')

         for row in M:
            rowlist= [x for x in row]
            matrix.append(rowlist)
         for index in range(len(matrix)):
             if (index==0):
                 pass
             else:
                 doors.append((matrix[index][2]))
    import matplotlib.pyplot as plt
    from math import *
    import numpy as np
    from numpy import *

    n=1
    a=np.arange(0,len(doors),n)
    y=[doors[int(x)] for x in a ]
    plt.scatter(a,y)
    plt.show()

I don't know python but I know CSV and programming and I will bet that you have values like 1,234.05 in your CSV file, where the python code does not like the comma... You may have to pre-process your CSV values, by replacing commas with nothing (removing the commas) to get it to parse the string properly into a float.

Post your exact error circumstances and I will review my answer. For example, in Sweden the number 1234.05 would be expressed as text as 1 234,05 - so you can see the parsing problems with multilingual data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM