Jaime Miranda Ramirez
Jaime Miranda Ramirez

Reputation: 315

How to ignore NaN values from a list?

I have an Excel file with a column that consists of measurements, for example:

Measurements

24235

325434

This one is empty, so it's a NaN value

45345

I'm extracting that column from excel into a python list, which will result in: list = ['24235', '325434', 'nan', '45435']. I want to ignore NaN values to be able to calculate the total measurement. I have this to prevent taking into consideration NaN values, but it's not working:

if list[i] != 'nan' or list[i] != float('NaN'):
    counter += int(list[i])

It's entering the if statement even when it's false. How can I fix this?

Upvotes: 1

Views: 4041

Answers (2)

AdamF
AdamF

Reputation: 2940

try, except ValueError

use try except and prevent the if..else old school style. this is more effecient and prevent you from writing long and complicated logic. pay attention to my comments inline

# init the counter
counter = 0    
# iterate on the list and pick list element one by one
for each in f:         
  try:
    # .. doWork() ... 
    counter += int(each)  # convert the element to int. if something wrong we will get ValueError which we will catch/except later.
  except ValueError:      # if we get valueerror exception that   means we hit nan. so we skip and continue. 
    pass   # you can use continue instead of using pass, both are valid!

We want to except only ValueError exceptions, because its raised by invalid int() conversion, like int(nan). for each other exception we want to raise it!

Upvotes: 0

PApostol
PApostol

Reputation: 2292

You can filter out the 'nan' elements like this:

original = ['24235', '325434', 'nan', '45435']
filtered = [int(element) for element in original if element != 'nan']
print(sum(filtered))

Output:

395104

Upvotes: 2

Related Questions