Home > Software engineering >  Dropnans from a list of numpy arrays in python
Dropnans from a list of numpy arrays in python

Time:01-27

I want to drop rows and columns which have all nan values on it from several numpy arrays. This is my code to do it when I have just one array with shape(101,101):

    array=array[:,~np.all(np.isnan(array), axis=0)] 
    array=array[~np.all(np.isnan(array), axis=1),:]

My first attempt was to create a for loop with a list of arrays:

    my_list=[array1,array2,array3,array4,array5]

    for array in my_list:
       array=array[:,~np.all(np.isnan(array), axis=0)]
       array=array[~np.all(np.isnan(array), axis=1),:]

but it is not working at all. Any ideas? Thank you in advance

CodePudding user response:

You can use the code below:

my_list = [array1,array2,array3,array4,array5]
my_list = my_list[~np.isnan(my_list)]

CodePudding user response:

I find this eventual answer:

 my_list=[array1,array2,array3,array4,array5]
 my_new_list=[]
 for arr in my_list:
    rows_nan=np.where(np.isnan(arr).all(axis=0))
    new_arr=np.delete(arr,rows_nan,axis=0)
    cols_nan=np.where(np.isnan(arr).all(axis=1))
    new_arr=np.delete(new_arr,cols_nan,axis=1)
    my_new_list.append(new_arr)

array1,array2,array3,array4,array5=my_new_list
  •  Tags:  
  • Related