我想弄清楚如何從我的數組中刪除nan值。它看起來像這樣:從數組中刪除nan值
x = [1400, 1500, 1600, nan, nan, nan ,1700] #Not in this exact configuration
我對python比較新,所以我仍然在學習。有小費嗎?
我想弄清楚如何從我的數組中刪除nan值。它看起來像這樣:從數組中刪除nan值
x = [1400, 1500, 1600, nan, nan, nan ,1700] #Not in this exact configuration
我對python比較新,所以我仍然在學習。有小費嗎?
如果您使用numpy的爲您的陣列,您還可以使用
x = x[numpy.logical_not(numpy.isnan(x))]
等價
x = x[~numpy.isnan(x)]
[感謝chbrown所添加的速記]
說明
內部函數numpy.isnan
返回一個布爾值/邏輯數組,其值True
到處都是x
不是數字。正如我們想要的相反,我們使用邏輯非運算符~
來獲得True
的數組,其中x
是的有效數字。
最後,我們使用這個邏輯數組索引到原始數組x
中,以檢索非NaN值。
試試這個:
import math
print [value for value in x if not math.isnan(value)]
欲瞭解更多,請閱讀List Comprehensions。
filter(lambda v: v==v, x)
作品既列表和numpy的陣列 因爲V = V僅楠
這是一種特別有用的破解方法,用於從具有混合類型的對象數組(例如字符串和nans)中過濾nans。 – 2015-06-29 14:15:01
非常乾淨的解決方案。 – Moondra 2017-10-17 19:48:28
做上述!
x = x[~numpy.isnan(x)]
或
x = x[numpy.logical_not(numpy.isnan(x))]
我發現,復位到相同的變量(x)並沒有刪除實際的nan值,而必須使用不同的變量。將它設置爲一個不同的變量移除了nans。 例如
y = x[~numpy.isnan(x)]
這很奇怪;根據[文檔](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing),布爾數組索引(這是),是**高級索引* *顯然「總是返回數據的副本」,所以你應該用新值覆蓋'x'(即沒有NaNs ...)。 你能提供更多關於爲什麼會發生這種情況的信息嗎? – jmetz 2017-03-24 10:35:03
對我來說@jmetz的答案不起作用,然而使用熊貓isnull()做了。
x = x[~pd.isnull(x)]
一個簡單的方法是:
numpy.nan_to_num(x)
文檔:https://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html
歡迎來到SO!你提出的解決方案並不能回答這個問題:你的解決方案用大量的NaN代替,而OP要求完全刪除這些元素。 – 2017-06-21 18:49:31
如圖別人
x[~numpy.isnan(x)]
作品。但是,如果numpy dtype不是本機數據類型,例如如果它是對象,它會拋出錯誤。在這種情況下,你可以使用熊貓。
x[~pandas.isnan(x)]
如果您使用numpy
# first get the indices where the values are finite
ii = np.isfinite(x)
# second get the values
x = x[ii]
或'x = x [numpy.isfinite(x)]' – lazy1 2012-07-23 22:29:06
或'x = x [〜numpy.isnan(x)]',相當於 mutzmatron的原始答案,但更短。如果你想保持你的無窮大,當然要知道'numpy.isfinite(numpy.inf)== False',但'〜numpy.isnan(numpy.inf)== True'。 – chbrown 2013-11-19 19:02:34
@ dax-felizv我同意@nbrown,NaN和Infinite在'numpy'中不一樣。 @chbrown - 感謝您指出'logical_not'的簡寫,但要注意它比較慢 - http://stackoverflow.com/questions/15998188/how-can-i-obtain-the-element-wise-logical-不是一個熊貓系列,http://stackoverflow.com/questions/13600988/python-tilde-unary-operator-as-negation-numpy-bool-array – jmetz 2013-11-20 19:45:54