Home > Blockchain >  Place numbers from a list to an array where the element is not a np.nan
Place numbers from a list to an array where the element is not a np.nan

Time:12-01

I have a list of numbers

a = [1, 2, 3, 4, 5]

and an existed array

b = [[np.nan, 10, np.nan], 
     [11,     12,     13], 
     [np.nan, 14, np.nan]]

How can I place the numbers from "list a" to the elements on array b that contains a number which I should get

c = [[np.nan, 1, np.nan], 
     [2,      3,      4], 
     [np.nan, 5, np.nan]]

Maybe it can be done with loops but I want to avoid it because the length of the list and the dimension of the array will change. However, the length of the list will always match the number of the elements that are not an np.nan in the array.

CodePudding user response:

Here is an approach to solve it without using loops.

First, we flatten the array b to convert it to a 1D array and then replace the none nan values with contents of a. Then, convert the array back to its initial shape.

flat_b = b.flatten()
flat_b[~np.isnan(flat_b)] = a
flat_b.reshape(b.shape)

CodePudding user response:

c = b
current = 0
for i in range(len(c)):
    for j in range(len(c[i])):
        if c[i][j] != np.nan and current < len(a):
            c[i][j] = a[current]
            current  = 1 

While this may look long and complicated, it actually only has a O(n) complexity. It just iterates through the 2D array and replaces the non-nan values with the current value from a.

CodePudding user response:

You can np.isnan to create a boolean mask. Then use it in indexing1.

m     = np.isnan(b)
b[~m] = a
print(b)
[[nan  1. nan]
 [ 2.  3.  4.]
 [nan  5. nan]]

1. NumPy's Boolean Indexing

  • Related