+1 vote
in Programming Languages by (74.9k points)
I want to combine two arrays: one with some NaN values and another with all integer values. I want to replace NaN with the corresponding value from the array containing all integer values. I want to use list comprehension for merging two arrays. How can I use "if else" with list comprehension?

E.g.

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

b=[11, np.nan, 13,np.nan, np.nan,16]

result=[11, 2, 13, 4, 5, 16]

1 Answer

+2 votes
by (353k points)
selected by
 
Best answer

Here is an example to show how to use list comprehension with "if else".

>>> import numpy as np
>>> a=[1,2,3,4,5,6]
>>> b=[11, np.nan, 13,np.nan, np.nan,16]
>>> [b[i] if b[i]>0 or b[i]<0 else a[i] for i in range(len(b))]
[11, 2, 13, 4, 5, 16]


...