Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Newbie question: .isnan
#1
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.
Reply
#2
use code tags, not quotes as quotes won't preserve indentation, see BBCODE in help: https://python-forum.io/misc.php?action=help
Reply
#3
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
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply
#4
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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 704 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 694 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Newbie question about switching between files - Python/Pycharm Busby222 3 608 Oct-15-2023, 03:16 PM
Last Post: deanhystad
  Newbie.... run for cover. OpenCV question Stevolution2023 2 977 Apr-12-2023, 12:57 PM
Last Post: Stevolution2023
  numpy newbie question bcwilly_ca 4 1,190 Feb-10-2023, 05:55 PM
Last Post: jefsummers
  Question from complete python's newbie Davicom 3 2,375 Jun-09-2021, 06:09 PM
Last Post: bowlofred
  Newbie question about running Python via GUI on OSX ejwjohn 8 3,516 Feb-05-2021, 03:20 PM
Last Post: Larz60+
  super newbie question: escape character tsavoSG 3 2,457 Jan-13-2021, 04:31 AM
Last Post: tsavoSG
  newbie question....importing a created class ridgerunnersjw 5 2,672 Oct-01-2020, 07:59 PM
Last Post: ridgerunnersjw
  Dumb newbie question JonEdward 5 3,257 Jul-22-2020, 10:06 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020