Python Forum

Full Version: Newbie question: .isnan
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Quote:import math
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
if not math.isnan(value):
filtered_data.append(value)

Not sure why this code doesn't work. It should filter numbers only when looped through list. Any idea?
I didn't receive any error message in my cmd, it just doesn't give any result.
use code tags, not quotes as quotes won't preserve indentation, see BBCODE in help: https://python-forum.io/misc.php?action=help
If you don't tell python to print it's not going to show anything.

import math

raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
    if not math.isnan(value):
        filtered_data.append(value)

print(filtered_data)#missing line of code
Here's another trick you may want to try

import math
from itertools import filterfalse

raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]

filtered_data = list(filterfalse(math.isnan, raw_data))
print(filtered_data)

filtered_data = list(filter(lambda x: not math.isnan(x), raw_data))
print(filtered_data)
Output:
[56.2, 51.7, 55.3, 52.5, 47.8] [56.2, 51.7, 55.3, 52.5, 47.8]