ValueError:无法将字符串转换为float:id

Loo*_*ast 61 python string floating-point

我正在运行以下python脚本:

#!/usr/bin/python

import os,sys
from scipy import stats
import numpy as np

f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    list1=[float(x) for x in l1]
    list2=[float(x) for x in l2]
    result=stats.ttest_ind(list1,list2)
    print result[1]
Run Code Online (Sandbox Code Playgroud)

但是我得到的错误如下:

ValueError: could not convert string to float: id
Run Code Online (Sandbox Code Playgroud)

我很困惑.当我在交互式部分中只尝试一行时,而不是使用脚本循环:

>>> from scipy import stats
>>> import numpy as np
>>> f=open('data2.txt','r').readlines()
>>> w=f[1].split()
>>> l1=w[1:8]
>>> l2=w[8:15]
>>> list1=[float(x) for x in l1]
>>> list1
[5.3209183842, 4.6422726719, 4.3788135547, 5.9299061614, 5.9331108706, 5.0287087832, 4.57...]
Run Code Online (Sandbox Code Playgroud)

我运作良好.

任何人都可以解释一下吗?谢谢

Anu*_*yal 43

显然,你的一些行没有有效的浮点数据,特别是某些行的文本id无法转换为浮点数.

当您在交互式提示中尝试它时,您只尝试第一行,因此最好的方法是打印出现此错误的行,您将知道错误的行,例如

#!/usr/bin/python

import os,sys
from scipy import stats
import numpy as np

f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    try:
        list1=[float(x) for x in l1]
        list2=[float(x) for x in l2]
    except ValueError,e:
        print "error",e,"on line",i
    result=stats.ttest_ind(list1,list2)
    print result[1]
Run Code Online (Sandbox Code Playgroud)


Sop*_*rez 18

我的错误非常简单:包含数据的文本文件在最后一行有一些空格(因此不可见).

作为grep的输出,我45 不仅仅是45

  • 空格和制表符是可见的;)换行符和类似内容不是,例如字符'\ n`,`\ r`。 (2认同)

Con*_*ngo 18

对于包含一列带逗号的数字的 Pandas 数据框,请使用以下命令:

df["Numbers"] = [float(str(i).replace(",", "")) for i in df["Numbers"]]
Run Code Online (Sandbox Code Playgroud)

因此像这样的值4,200.42将被转换为4200.42浮点数。

奖励 1:这很快

好处 2:如果将该数据帧保存为Apache Parquet格式,则空间效率更高。


Ble*_*der 11

这个错误非常冗长:

ValueError: could not convert string to float: id
Run Code Online (Sandbox Code Playgroud)

在文本文件的某处,一行中包含单词id,无法真正转换为数字.

您的测试代码有效,因为该单词id不存在line 2.


如果要捕获该行,请尝试使用此代码.我清理了你的代码:

#!/usr/bin/python

import os, sys
from scipy import stats
import numpy as np

for index, line in enumerate(open('data2.txt', 'r').readlines()):
    w = line.split(' ')
    l1 = w[1:8]
    l2 = w[8:15]

    try:
        list1 = map(float, l1)
        list2 = map(float, l2)
    except ValueError:
        print 'Line {i} is corrupt!'.format(i = index)'
        break

    result = stats.ttest_ind(list1, list2)
    print result[1]
Run Code Online (Sandbox Code Playgroud)


Tom*_*oth 6

也许您的数字实际上不是数字,而是伪装成数字的字母?

就我而言,我使用的字体表示“ l”和“ 1”看起来非常相似。我有一个像“ l1919”的字符串,我以为是“ 11919”,这使事情搞砸了。


Joã*_*mes 6

最短路线:

df["id"] = df['id'].str.replace(',', '').astype(float) - 如果“,”是问题所在

df["id"] = df['id'].str.replace(' ', '').astype(float)- 如果空格是问题所在


Mat*_*ick 5

您的数据可能不是您所期望的——似乎您期望但没有得到浮动。

找出发生这种情况的一个简单解决方案是在 for 循环中添加一个 try/except :

for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    try:
      list1=[float(x) for x in l1]
      list2=[float(x) for x in l2]
    except ValueError, e:
      # report the error in some way that is helpful -- maybe print out i
    result=stats.ttest_ind(list1,list2)
    print result[1]
Run Code Online (Sandbox Code Playgroud)