1

My goal is to fill a 2D array with values from a 1D array that exactly matches the pattern of values in the 2D array. For example:

array_a = 
([[nan,nan,0],
 [0,nan,0],
 [nan,0,0], 
 [0,0,nan]])

array_b = 
([0.324,0.254,0.204,
0.469,0.381,0.292,
0.550])

And I want to get this:

array_c = 
([[nan,nan,0.324],
 [0.254,nan,0.204],
 [nan,0.469,0.381], 
 [0.292,0.550,nan]])

The number of values that need to be filled in array_a will exactly match the number of values in array_b. The main issue is that I want to have the nan values in the appropiate order throughout the array and I'm not sure how best to do that.

3
  • 1
    flatten your array_a, get the indices of non nan elements, replace the elements at these indices with array_b and reshape back Commented Aug 29, 2018 at 20:50
  • @Bazingaa, no need to flatten or reshape. Boolean indexing flattens automatically. Commented Aug 29, 2018 at 21:04
  • @hpaulj: Thanks for the info! Commented Aug 29, 2018 at 21:05

3 Answers 3

3

boolean indexing does the job nicely:

Locate the nan:

In [229]: mask = np.isnan(array_a)
In [230]: mask
Out[230]: 
array([[ True,  True, False],
       [False,  True, False],
       [ True, False, False],
       [False, False,  True]])

boolean mask applied to the array produces a 1d array:

In [231]: array_a[~mask]
Out[231]: array([0., 0., 0., 0., 0., 0., 0.])

Use that same array in a set context:

In [232]: array_a[~mask]=array_b
In [233]: array_a[~mask]
Out[233]: array([0.324, 0.254, 0.204, 0.469, 0.381, 0.292, 0.55 ])
In [234]: array_a
Out[234]: 
array([[  nan,   nan, 0.324],
       [0.254,   nan, 0.204],
       [  nan, 0.469, 0.381],
       [0.292, 0.55 ,   nan]])
Sign up to request clarification or add additional context in comments.

Comments

2

You can also do:

np.place(array_a, array_a == 0, array_b)

array_a

array([[  nan,   nan, 0.324],
       [0.254,   nan, 0.204],
       [  nan, 0.469, 0.381],
       [0.292, 0.55 ,   nan]])

Comments

1

This should do the trick, although there might be a pre-written solution or a list comprehension to do the same.

import numpy as np
b_index = 0
array_c = np.zeros(np.array(array_a).shape)
for row_index, row in enumerate(array_a):
    for col_index, col in enumerate(row):
        if not np.isnan(col):
            array_c[row_index, col_index] = array_b[b_index]
            b_index += 1
        else:
            array_c[row_index, col_index] = np.nan

>>> print(array_c)
[[  nan   nan 0.324]
 [0.254   nan 0.204]
 [  nan 0.469 0.381]
 [0.292 0.55    nan]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.