我想弄清楚如何从我的数组中删除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