Reputation: 431
How to insert a value right before the nan in a list having nan at the end of the list?
random = [9,1,5, ... 7,6,3,2,5, nan, nan, nan, ...]
random.append(8181) < somehow add function here
results should be, the value inserted before first nan
random = [9,1,5, ... 7,6,3,2,5,8181, nan, nan, nan, ...]
Upvotes: 1
Views: 490
Reputation: 2665
If we know how many NaN
values we have then we can use insert
with a negative count.
my_list.insert(-nan_count, 8181)
If we don't know the count, then we need to find out the last position.
for i,v in enumerate(reversed(my_list)): # loop backwards
if v==v:
a.insert(len(a)-i, 8181) # found the first non NaN, insert just before this
break # only do it for the first item
Upvotes: 1
Reputation: 362627
Traverse the list from end to find the correct position, then use list.insert
:
import math
i = 0
while math.isnan(random[i - 1]):
i -= 1
random.insert(i, 8181)
Upvotes: 3