2017-08-15 1033 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]