1

In numpy, how would you merge the following two arrays on the non-nan values, resulting in third array?

Array 1 (shape: r, c):

array([[nan,  1.,  1., nan, nan, nan],
       [nan, nan, nan,  1.,  1., nan],
       [nan, nan,  1.,  1., nan, nan],
       ...,
       [nan, nan, nan,  1.,  1., nan],
       [nan, nan, nan,  1.,  1., nan],
       [nan, nan,  1.,  1., nan, nan]])

Array 2: (shape r, 2)

array([[ 0.76620125, 59.14934823],
       [ 2.52819832, 43.63809538],
       [ 1.9656387 , 25.62212163],
       ...,
       [ 2.55076928, 43.04276273],
       [ 2.62058763, 22.14260189],
       [ 1.8050997 , 51.72144285]])

Resulting array: (shape r, c)

array([[nan,  0.76620125, 59.14934823, nan, nan, nan],
       [nan, nan, nan,   2.52819832, 43.63809538, nan],
       [nan, nan,   1.9656387, 25.62212163, nan, nan],
       ...,
       [nan, nan, nan,   2.55076928, 43.04276273, nan],
       [nan, nan, nan,   2.62058763, 22.14260189, nan],
       [nan, nan,   1.8050997 , 51.72144285, nan, nan]])
a_b
  • 1,828
  • 5
  • 23
  • 37

1 Answers1

0

this should do, if a is your first array and b the second one:

a[~np.isnan(a)] = b.ravel()
filippo
  • 5,197
  • 2
  • 21
  • 44
  • In `np.where()` documentation: "When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses.". Also either `np.where()` or `np.nonzero()` is not really needed. – norok2 Sep 30 '22 at 11:21
  • 1
    Also, I'd use `np.ndarray.ravel()` instead of `np.ndarray.flatten()` since the latter creates a copy, which I do not think it is beneficial. https://stackoverflow.com/questions/28930465/what-is-the-difference-between-flatten-and-ravel-functions-in-numpy – norok2 Sep 30 '22 at 11:30