2016-08-15 100 views
1

我有以下列表中的Python:将NaN和字符串列表转换为int?

mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] 

我想一切转换为int。我想用斜线字符串取第一个值。

这是我已经试过:

newlist = [int(str(x).split('/')[0]) for x in mylist] 

但这并不对NaN价值的工作。处理字符串和NaN值的最佳方法是什么?

+2

你想要的NaN转换为int。那么你想让NaN转换成什么样的int? – khelwood

+0

@ khelwood:人们可能会问它应该是什么样的浮动,但它确实是一个浮动。 – zondo

+0

@zondo可以,但它已经是一个浮点数了,他试图将它转换为int。 – khelwood

回答

0

pandas.isnull另一种解决方案:

import pandas as pd 
import numpy as np 

mylist = [np.nan, u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] 

newList = [0 if pd.isnull(item) else int(str(item).split('/')[0]) for item in mylist] 
print(newList) 
[0, 2, 3, 1, 4, 1, 2, 0] 

大熊猫的解决方案替代NaN'0'通过Series.fillna,由str.split劈裂,得到名单的第一要素由str[0]和铸造用astype

mylist = [np.nan, u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] 

newList = pd.Series(mylist).fillna('0').str.split('/').str[0].astype(int) 
print(newList) 
0 0 
1 2 
2 3 
3 1 
4 4 
5 1 
6 2 
7 0 
dtype: int32 

print(newList.tolist()) 
[0, 2, 3, 1, 4, 1, 2, 0] 
1

您可以在数学库中使用isnan函数来检查一个浮点数是否为NaN,但是它将浮点数作为参数,因此您必须首先将您的项目转换为浮点数。您可以选择是否跳过NaN,或将它们保存为某个默认值。在下面的NaN的代码保存为INT 0

import math 

mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] 

newlist = [] 

for item in mylist: 

    x = float(str(item).split('/')[0]) 

    if not math.isnan(x): 
     newlist.append(int(x)) 
    else: 
     newlist.append(0) 

print newlist 
0

我们知道,楠永远!= NaN的
用下面的办法一切转换成整数

mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] 
newList = [0 if (not item or (item != item)) else int(str(item).split('/')[0]) for item in mylist] 
print(newList) 

输出:

[0, 2, 3, 1, 4, 1, 2, 0]