首页 > 解决方案 > ValueError:在读取 csv 文件时无法将字符串转换为浮点数,如何解决?

问题描述

这种类型的问题已经被问过好几次了。不过,我找不到与我的案例类似的问题。如果有类似的,请告诉我。

蟒蛇文件是

import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import csv
import numpy as np

x = []
y = []

with open('example2.txt','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=' ')
    for row in plots:
        #print(row[0],type(row[0]))
        x.append(float(row[0]))
        y.append(float(row[1]))

example2.txt 是

0.0  0.5
0.1  0.6

我收到一条错误消息

Traceback (most recent call last):
  File "plot.py", line 14, in <module>
    y.append(float(row[1]))
ValueError: could not convert string to float:

某些链接,例如ValueError: could not convert string to float: id,表明原因是值中有额外的空间。我无法通过打印 row[0] 值来找到额外的空间:(

标签: pythonpython-3.xcsv

解决方案


推荐阅读