Home > Blockchain >  How to fill arrays with nan values while comparing two arrays
How to fill arrays with nan values while comparing two arrays

Time:09-02

I have two numpy arrays like

    import numpy as np
    a=np.array([[ 3, nan,  4,  1,  4,  2,  2,  3],
                [ 2, nan,  1,  3, nan,  4,  4,  3],
                [ 3,  2, nan,  4, nan, nan,  3,  4],
                [ 2,  2,  2, nan,  1,  1 ,nan,  2]])
  
    b =np.array( [[ 2,  3,  2, 2,  3,  3,  3,  3],
                 [ 3,  3,  1,  4,  1,  4,  1, 7],
                 [ 4,  2, 5,  4,  4,  3, 10,  4],
                 [ 2,  4,  2,  1,  4,  1,  3, nan]])

Requirement :

Where element value is nan in array a is assign in to array b in the same position.

expected output:

             [[2, nan, 2, 2, 3, 3, 3, 3],
              [3, nan, 1, 4, nan, 4, 1, 7],
              [4, 2, nan, 4, nan, nan, 10, 4],
              [2, 4, 2, 1, nan, 1, nan, nan]]

CodePudding user response:

How about this:

b[np.isnan(a)] = float('nan')

If you want a copy of b instead of changing it inplace, use this:

c = np.where(np.isnan(a), a, b)

CodePudding user response:

c = b.copy()
c[np.isnan(a)] = np.nan
  • Related