从数组中删除 nan 值 [英] Removing nan values from an array

查看:48
本文介绍了从数组中删除 nan 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何从我的数组中删除 nan 值.我的数组看起来像这样:

I want to figure out how to remove nan values from my array. My array looks something like this:

x = [1400, 1500, 1600, nan, nan, nan ,1700] #Not in this exact configuration

如何从 x 中删除 nan 值?

How can I remove the nan values from x?

推荐答案

如果你的数组使用 numpy,你也可以使用

If you're using numpy for your arrays, you can also use

x = x[numpy.logical_not(numpy.isnan(x))]

等价于

x = x[~numpy.isnan(x)]

[感谢 chbrown 添加的速记]

[Thanks to chbrown for the added shorthand]

说明

内部函数 numpy.isnan 返回一个布尔/逻辑数组,该数组在 x 不是的任何地方都具有值 True数字.正如我们想要的相反,我们使用逻辑非运算符 ~ 来获取一个数组,其中 Truex 一个有效的数字.

The inner function, numpy.isnan returns a boolean/logical array which has the value True everywhere that x is not-a-number. As we want the opposite, we use the logical-not operator, ~ to get an array with Trues everywhere that x is a valid number.

最后,我们使用这个逻辑数组索引到原始数组 x,以检索非 NaN 值.

Lastly we use this logical array to index into the original array x, to retrieve just the non-NaN values.

这篇关于从数组中删除 nan 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆