Issue
I am having trouble figuring out what the equivalent of is.na() function in r to python is. I am using np.nan but it does not work. What I am trying to do is add all the elements in a list before I reach an NA element. Here is my problem:
import numpy as np
x=[3,6,7,np.nan,-3,0]
k=len(x)
total_before_NA=0
for i in range(0,k):
if (np.nan(x[i])):
break
total_before_NA= total_before_NA + x[i]
print(total_before_NA)
The answer I should be getting is 16 without using the sum function. Am I using the correct function? What am I doing wrong?
Solution
You can use np.isnan()
to locate NaN
, and then np.argwhere()
to find the indices. Find the first index with min()
and finally use np.sum
on the slice before the first index with NaN
:
index_first_nan = np.argwhere(np.isnan(x)).min()
np.sum(x[0:index_first_nan])
Answered By - ML-Nielsen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.