Python-将负小数从字符串转换为浮点数 [英] Python - Convert negative decimals from string to float

查看:935
本文介绍了Python-将负小数从字符串转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to read in a large number of .txt files, each of which contains a decimal (some are positive, some are negative), and append these into 2 arrays (genotypes and phenotypes). Subsequently, I wish to perform some mathematical operations on these arrays in scipy, however the negative ('-') symbol is causing problems. Specifically, I cannot convert the arrays to float, because the '-' is being read as a string, causing the following error:

ValueError: could not convert string to float:

这是我当前编写的代码:

Here is my code as it's currently written:

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是​​问题吗?有没有更好的替代方法?

I am fairly certain at this point that it is the negative sign that is causing the problem, but it is not clear to me why. Is my use of Linecache the problem here? Is there an alternative method that would be better?

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']


推荐答案

问题似乎出在空字符串或空格,从错误消息中可以明显看出

The issue seems to be with empty string or space as evident from your error message

ValueError: could not convert string to float:

要使其工作,请将地图转换为列表理解

To make it work, convert the map to a list comprehension

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

用空字符串表示

float() float()会产生值错误,因此,如果 gene_array phen_array 有空间,这会在转换为float时引发错误

float(" ") or float("") would give value errors, so if any of the items within gene_array or phen_array has space, this will throw an error while converting to float

空字符串,如


  • 空行或空白行

  • 空白行在开头或结尾

这篇关于Python-将负小数从字符串转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆