Почему Python показывает 'ValueError: не удалось преобразовать строку в float'?


У меня есть CSV, содержащий числа, которые я пытаюсь преобразовать в поплавки.

filename = "filename.csv"
enclosed_folder = "path/to/Folder"
full_path = os.path.join(enclosed_folder,filename)

with open(full_path) as input_data:
    temp = input_data.readlines()
    n = len(temp) #int(temp.pop(0))
    matrix = [x.split(" ") for x in temp]
    for i in range(n):
        for j in range(n):
            matrix[i][j] = float(matrix[i][j])
    input_data.close()

Когда я открываю файл в любом текстовом редакторе, он не показывает n в конце каждой строки.

Введите описание изображения здесь

Но запуск кода python показывает 'ValueError: не удалось преобразовать строку в float 'из-за' n', присутствующего в конце каждой строки.

Traceback (most recent call last):
  File "hierarchical-clustering.py", line 37, in <module>
    matrix[i][j] = float(matrix[i][j])
ValueError: could not convert string to float: '1,0.058824,0.076923,0.066667,0.055556,0.058824,0.071429,0.052632,0.076923,0.0625,0.0625,0.055556,0.055556,0.05,0.066667,0,0,0.055556,0.0625,0.058824,0.058824,0.047619,0.055556,0.0625,0,0.052632,0.066667,0.055556,0.0625,0.058824,0.041667,0.066667,0.058824,0.071429,0.066667,0.076923,0,0.083333,0.052632,0.071429,0.076923,0,0.0625,0.076923,0.058824,0.076923,0.055556,0,0.0625,0.071429,0.0625,0.0625,0.083333,0,0,0,0.058824,0.0625,0,0.058824,0.0625,0.0625,0.066667,0.0625,0.052632,0.066667,0.076923,0.058824,0.071429,0.066667,0.058824,0.071429,0.058824,0.071429,0.058824,0.071429,0.071429n'

Итак, как я могу исправить эту ошибку?

EDIT: я использовал strip() , а также rstrip(), как предложено в некоторых из ответов убрать пробелы, но все равно ошибка никуда не делась:

Traceback (most recent call last):
  File "hierarchical-clustering.py", line 37, in <module>
    matrix[i][j] = float(matrix[i][j].rstrip())
ValueError: could not convert string to float: '1,0.058824,0.076923,0.066667,0.055556,0.058824,0.071429,0.052632,0.076923,0.0625,0.0625,0.055556,0.055556,0.05,0.066667,0,0,0.055556,0.0625,0.058824,0.058824,0.047619,0.055556,0.0625,0,0.052632,0.066667,0.055556,0.0625,0.058824,0.041667,0.066667,0.058824,0.071429,0.066667,0.076923,0,0.083333,0.052632,0.071429,0.076923,0,0.0625,0.076923,0.058824,0.076923,0.055556,0,0.0625,0.071429,0.0625,0.0625,0.083333,0,0,0,0.058824,0.0625,0,0.058824,0.0625,0.0625,0.066667,0.0625,0.052632,0.066667,0.076923,0.058824,0.071429,0.066667,0.058824,0.071429,0.058824,0.071429,0.058824,0.071429,0.071429'
3 2

3 ответа:

Ошибка вызвана вашим разбором строк. Вы разделяете на пробелы, а не запятые, что должно произойти в соответствии с вашим скриншотом. Ключ смотрит на возвращенную ошибку. Он пытается преобразовать всю линию из строки в поплавок.

Изменение:

matrix = [x.split(" ") for x in temp]

Кому:

matrix = [x.split(",") for x in temp]

Вы можете использовать strip() чтобы удалить пробелы из строки.

matrix[i][j] = float(matrix[i][j].strip())

Если запятые беспокоят вас, вы можете захотеть .split(',') с запятыми, а не пробелами:

matrix = [x.strip().split(",") for x in temp]

Удалите символ новой строки с помощью rstrip() следующим образом:

matrix[i][j] = float(matrix[i][j].rstrip())