1

我需要读取大量 .txt 文件,每个文件都包含一个小数(有些是正数,有些是负数),并将它们附加到 2 个数组(基因型和表型)中。随后,我希望在 scipy 中对这些数组执行一些数学运算,但是负号('-')会导致问题。具体来说,我无法将数组转换为浮点数,因为“-”被读取为字符串,导致以下错误:

ValueError: could not convert string to float:

这是我目前编写的代码:

import linecache

gene_array=[]
phen_array=[]

for i in genotype:

   for j in phenotype:

      genotype='/path/g.txt'
      phenotype='/path/p.txt'

      g=linecache.getline(genotype,1)
      p=linecache.getline(phenotype,1)

      p=p.strip()
      g=g.strip()

      gene_array.append(g)
      phen_array.append(p)

  gene_array=map(float,gene_array)
  phen_array=map(float,phen_array)

在这一点上,我相当确定这是导致问题的负号,但我不清楚为什么。我使用 Linecache 是这里的问题吗?有没有更好的替代方法?

的结果

print gene_array

['-0.0448022516321286', '-0.0236187263814157', '-0.150505384829925', '-0.00338459268479522', '0.0142429109897682', '0.0286253352284279', '-0.0462358095345649', '0.0286232317578776', '-0.00747425206137217', '0.0231790239373428', '-0.00266935581919541', '0.00825077426011094', '0.0272744527203547', '0.0394829854063242', '0.0233109171715023', '0.165841084392078', '0.00259693465334536', '-0.0342590874424289', '0.0124600520095644', '0.0713627590092807', '-0.0189374898081401', '-0.00112750710611284', '-0.0161387333242288', '0.0227226505624106', '0.0382173405035751', '0.0455518646388402', '-0.0453048799717046', '0.0168570746329513']
4

3 回答 3

3

从您的错误消息中可以看出,问题似乎与空字符串或空格有关

ValueError: could not convert string to float:

为了使它工作,将地图转换为列表理解

gene_array=[float(e) for e in gene_array if e]
phen_array=[float(e) for e in phen_array if e]

通过空字符串表示

float(" ")orfloat("")会给出值错误,因此如果其中的任何项目gene_arrayphen_array有空间,这将在转换为浮点数时引发错误

空字符串可能有很多原因,例如

  • 空行或空行
  • 开头或结尾的空行
于 2013-01-03T19:14:35.707 回答
0

错误消息中没有任何内容表明这-是问题所在。最可能的原因是gene_array和/或phen_array包含一个空字符串 ( '')。

如文档中所述,linecache.getline()

将返回''错误(找到的行将包含终止换行符)。

于 2013-01-03T19:10:33.803 回答
0

这个问题绝对不是负面的。Python 可以毫无问题地转换带有负号的字符串。我建议您针对浮动 RegEx 运行每个条目,看看它们是否都通过了。

于 2013-01-03T19:11:59.227 回答