Home > Back-end >  What is the equivalent of is.na() function in r to python?
What is the equivalent of is.na() function in r to python?

Time:10-15

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?

CodePudding user response:

Solution

You can use np.isnan to check for NaN values.

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.isnan(x[i])):
        break
    total_before_NA= total_before_NA   x[i]

print(total_before_NA)

CodePudding user response:

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])

CodePudding user response:

I don't know any R, but it seems that what you want to do is sum up all the values in your list that come before the NA. If so, then I'd suggest to use index() to obtain the index of that first NA and then simple slicing and summing:

i = x.index(np.nan)
total_before_NA = sum(x[:i])

That will make total_before_NA 16 in your example.

  • Related