2017-08-15 594 views
0

尝试使用熊猫处理项目时遇到了问题。我有一个nan值的列表,我无法删除它。从列表中删除nan

我曾尝试:

incoms=data['int_income'].unique().tolist() 
incoms.remove('nan') 

但它没有工作:

list.remove(X):在列表”

列表中移除x不incoms是如下:

[75000.0, 50000.0, 0.0, 200000.0, 100000.0, 25000.0, nan, 10000.0, 175000.0, 150000.0, 125000.0] 
+0

我想你需要['.dropna'(https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna。 html) –

+0

尝试'pd.dropna()' – gobrewers14

+0

如果我的(或其他)答案有帮助,请不要忘记[接受](http://meta.stackexchange.com/a/5235/295067)它 - 点击答案旁边的复选标记('✓')将其从灰色变为灰色填充。谢谢。 – jezrael

回答

1

你可以做的是简单地得到一个干净列表,你不把,一旦转换为字符串值,是'nan'。

的代码将是:

incoms = [incom for incom in incoms if str(incom) != 'nan'] 
4

我认为你需要dropna用于去除NaN S:

incoms=data['int_income'].dropna().unique().tolist() 
print (incoms) 
[75000.0, 50000.0, 0.0, 200000.0, 100000.0, 25000.0, 10000.0, 175000.0, 150000.0, 125000.0] 

如果所有值都只能为整数:

incoms=data['int_income'].dropna().astype(int).unique().tolist() 
print (incoms) 
[75000, 50000, 0, 200000, 100000, 25000, 10000, 175000, 150000, 125000] 

,或者通过numpy.isnan选择所有非NaN值删除NaN S:

a = data['int_income'].unique() 
incoms= a[~np.isnan(a)].tolist() 
print (incoms) 
[75000.0, 50000.0, 0.0, 200000.0, 100000.0, 25000.0, 10000.0, 175000.0, 150000.0, 125000.0] 

a = data['int_income'].unique() 
incoms= a[~np.isnan(a)].astype(int).tolist() 
print (incoms) 
[75000, 50000, 0, 200000, 100000, 25000, 10000, 175000, 150000, 125000] 

纯Python的解决方案 - slowier如果大DataFrame

incoms=[x for x in list(set(data['int_income'])) if pd.notnull(x)] 
print (incoms) 
[0.0, 100000.0, 200000.0, 25000.0, 125000.0, 50000.0, 10000.0, 150000.0, 175000.0, 75000.0] 

incoms=[int(x) for x in list(set(data['int_income'])) if pd.notnull(x)] 
print (incoms) 
[0, 100000, 200000, 25000, 125000, 50000, 10000, 150000, 175000, 75000]