15
I have an array of values that can include several numpy.Nan:
import numpy as np
a = np.array ( [1, 2, np.nan, 4] )
And I want to iterate over your items to create a new array without np.Nan.
The way I know to create arrays dynamically is to create an array of zeros (np.zeros()
) and fill it with content of interest a posteriori.
The way I do, I have to iterate the array a
twice: once to count how many np.nan
s I will find and reduce that number of the dimension of the array b
; and the second iteration to popular the array b
:
# Contando quantos nan's
count = 0
for e in a:
if np.isnan(e):
count += 1
# criando o array vazio do tamanho certo
size = a.shape[0]
b = np.zeros( (size - count, ) )
# populando o array com o conteúdo pertinente
ind = 0
for e in a:
if not np.isnan(e):
b[ind] = e
ind += 1
I imagine it is also possible to do this by converting a
to the list (since it is one-dimensional) and filter this list to the list b
then convert it to array.
But there is a more efficient way to do this only with arrays?
An alternative would be
filter(lambda n: ~np.isnan(n), a)
, but I believe that the boolean indexing suggested by @rodrigorgs is more efficient. :)– Paulo Freitas