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: one to count how many np.nan
s I'm going to find and reduce that number of the array size b
; and the second iteration to populate 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 you can also do this by converting a
to list (since it is one-dimensional) and filter that list to the b
list by converting it to array.
But is there a more efficient way to do this only with arrays?