2017-06-19 71 views
0
A=[None, '0.50', '2', '4', '6', '0', '0', '0', '0.00', '0', '0', '0', '5', '1', '5', '5', '1', '1', '0', '1', '2', '2', '2', '0 (1:1)', '0', '0', '2', '2', '0', '0', '1', '2', '0'] 
B=[] 
for elem in A: 
    if elem is not None: 
     B.append(float(elem.strip("''"))) 
    else: 
     B.append(elem) 
print B 

我有一个列表,其中包含上面显示的值。当我尝试使用熊猫添加到Excel表格时,它将被添加为文本而不是float或int。我想删除引号,以便它不会被视为excel表格中的文本,我知道它可以使用split来完成,如果我尝试将所有这些转换为float,它将引发此'0( 1:1)'元素说无效文字为float。我该如何处理?如何在将列表中的文字转换为浮点时处理异常?

+0

你关心物品'0(1:1)'吗? – ILostMySpoon

+0

那么你想用'0(1:1)'来做什么? – khelwood

+0

你提到熊猫 - 你看过[pandas.to_numeric](https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.to_numeric.html)并指定错误='胁迫'吗? –

回答

1

更简单的解决方案是将包裹for体在try-except和附加None或原始值(elem)如果它没有特定的迭代:

A = [None, '0.50', '2', '4', '6', '0', '0', '0', '0.00', '0', '0', '0', '5', '1', '5', '5', '1', '1', '0', '1', '2', '2', '2', '0 (1:1)', '0', '0', '2', '2', '0', '0', '1', '2', '0'] 

B = [] 

for elem in A: 
    try: 
     B.append(float(elem)) 
    except (ValueError, TypeError) as error: 
     B.append(elem) 

     # Or, if you don't want to preserve the non-numeric values: 

     # B.append(None) 

print(B) 

一个ValueError会被抛出时不能解析为float,而elemNone时将丢弃TypeError

一样,如果使用和ifelemNone和两个异常可以持续进行处理(假设这是你想要的)你不需要检查。

注意不需要.strip("''"),因为它实际上没有做任何事情。 According to the docs, strip() will...

Return a copy of the string with the leading and trailing characters removed.

也就是说,它会尝试从一开始就和你的价值观的结尾处,删除'',但没有你的价值观的开始或两个单引号结束。实际上,它们中的任何一个都包含引号,它们周围的那些只是表示字符串的方式,但不是它们的价值的一部分。

此外,float()将自动采取Float转换一个数字('1')的字符串表示的护理。

+0

我想在列表中保留0(1:1),我不希望它们为空。 – user1681102

+0

@ user1681102然后使用'except'块中的注释掉的代码:'B.append(elem)' – Danziger

+0

它将仍然以字符串格式对吗? – user1681102

0

你可以使用:

def isfloat(element): 
    try: 
     return float(element) 
    except ValueError: 
     return False 

B = [] 
A = [None, '0.50', '2', '4', '6', '0', '0', '0', '0.00', '0', '0', '0', '5', '1', '5', '5', '1', '1', '0', '1', '2', '2', '2', '0 (1:1)', '0', '0', '2', '2', '0', '0', '1', '2', '0'] 
for x in A: 
    floatval = isfloat(element) 
    if floatval: 
     B.append(floatval) 

或者,如果你喜欢一个列表理解(有两个浮筒的冗余):

B = [float(x) for x in A if isfloat(x) not in [False]] 

几个陷阱,但:isfloat("NaN")isfloat("inf")isfloat(True)不是返回False


另一种解决方案使用发电机功能:

def strtofloat(your_list): 
    for i in your_list: 
     try: 
      yield float(i) 
     except (TypeError, ValueError): 
      pass 

B = list(strtofloat(A)) 

一个更通用的解决方案考虑到多种类型:

def strtofloat(your_list, allowed_types): 
    for i in your_list: 
     try: 
      yield f[0](i) 
     except (TypeError, ValueError): 
      try: 
       yield f[1](i) 
      except (TypeError, ValueError): 
       pass 

B = list(strtofloat(A), [int, float]) 

如果您传递[float, int],而不是[int, float],它全部有效int s到float s。

+0

这似乎有点多余......调用两次“float”。这应该可能只是一个for循环,而不是试图把它变成列表理解。 –

+0

@ juanpa.arrivillaga是的,我想。编辑。 –

+1

或者循环并产生值并传递例外...然后应用列表(isfloat(whatever)) –

0

可以使用literal_evalast模块,并使用一个try ... except块这样例如:

from ast import literal_eval 

A=[None, '0.50', '2', '4', '6', '0', '0', '0', '0.00', '0', '0', '0', '5', '1', '5', '5', '1', '1', '0', '1', '2', '2', '2', '0 (1:1)', '0', '0', '2', '2', '0', '0', '1', '2', '0'] 

def evaluate(a): 
    for k in a: 
     try: 
      # Or if you want: use yield float(k) 
      yield literal_eval(k) 
     except ValueError: 
      yield k 
     except SyntaxError: 
      yield k 

>>> list(evaluate(A)) 
[None, 0.5, 2, 4, 6, 0, 0, 0, 0.0, 0, 0, 0, 5, 1, 5, 5, 1, 1, 0, 1, 2, 2, 2, '0(1:1)', 0, 0, 2, 2, 0, 0, 1, 2, 0] 
+0

我得到TypeError:'list'对象不可调用 – user1681102

+0

您是否运行了我在我的答案中给出的相同示例?或者你有不同的意见?因为这个例子运行良好,没有任何错误。 –

+0

是的,我已经跑了相同的例子。 – user1681102