For instance, I have
list_a = [10, 20, 30, 40, 50, 60, 70]
list_b = [10, 11, 12, nan, nan, nan, 16]
list_b
is the indices of list_a
, starting from 10 instead of 0. The nan
elements means that the corresponding data is not of interest. The list I need is
list_c = [10, 20, 30, nan, nan, nan, 70]
. How can I get it?
A simple list comprehension should get you what you want:
>>> [list_a[i] if list_b[i] is not nan else nan for i, val in enumerate(list_b)]
[10, 20, 30, nan, nan, nan, 70]
Here we’re effectively ignoring the non-nan
values in list_b
; we’re just treating it like a list of “boolean” nan
/not-nan
values.
I guess a more accurate reflection of what you wanted would be:
>>> [list_a[list_b[i]-10] if list_b[i] is not nan else nan for i, val in enumerate(list_b)]
[10, 20, 30, nan, nan, nan, 70]
But that gets you the same thing as long as the values in list_b
are just an incrementing sequence (when they’re not nan
).
4