Eliminación de valores nan de una matriz


Quiero averiguar cómo eliminar los valores nan de mi matriz. Se ve algo como esto:

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

Soy relativamente nuevo en python, así que todavía estoy aprendiendo. Algún consejo?

Author: Mad Physicist, 2012-07-24

8 answers

Si está usando numpy para sus matrices, también puede usar

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

Equivalente

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

[Gracias a chbrown por la taquigrafía añadida]

Explicación

La función interna, numpy.isnan devuelve una matriz booleana/lógica que tiene el valor True en todas partes que x no es un número. Como queremos lo contrario, usamos el operador logical-not, ~ para obtener una matriz con True s en todas partes que x es un número válido.

Por último, utilice esta matriz lógica para indexar en la matriz original x, para recuperar solo los valores no NaN.

 223
Author: jmetz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 11:15:26
filter(lambda v: v==v, x)

Funciona tanto para listas como para matriz numpy desde v!= v solo para NaN

 36
Author: udibr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-16 15:46:36

Prueba esto:

import math
print [value for value in x if not math.isnan(value)]

Para más información, lea en Listas de Comprensiones.

 33
Author: liori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-23 21:39:59

Para mí la respuesta de @jmetz no funcionó, sin embargo usando pandas isnull() sí.

x = x[~pd.isnull(x)]
 8
Author: Daniel Kislyuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-18 14:37:51

Haciendo lo anterior:

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

O

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

Encontré que restablecer a la misma variable (x) no eliminaba los valores reales de nan y tenía que usar una variable diferente. Al establecerlo en una variable diferente, se eliminaron las nan. por ejemplo,

y = x[~numpy.isnan(x)]
 4
Author: melissaOu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-23 20:35:51

Como lo muestran otros

x[~numpy.isnan(x)]

Funciona. Pero lanzará un error si el dtype numpy no es un tipo de datos nativo, por ejemplo, si es object. En ese caso puedes usar pandas.

x[~pandas.isnan(x)]
 2
Author: koliyat9811,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-25 12:55:01

Si estás usando numpy

# first get the indices where the values are finite
ii = np.isfinite(x)

# second get the values
x = x[ii]
 2
Author: aloha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-16 09:19:02

Una forma más simple es:

numpy.nan_to_num(x)

Documentación: https://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html

 -3
Author: Bruno Rodrigues de Oliveira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-21 18:03:06