2

How to I count the occurrences of NaN in my list? My data looks like this:

[365788, 267102, 170941, 'NaN', 243293, 267093, 'NaN', 370448, 'NaN', 197091]
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Nate
  • 2,113
  • 5
  • 19
  • 25
  • 5
    Are those really `'NaN'` strings in your list, rather than actual floating-point NaNs? (If so, then why?) If they're real floating-point NaNs, ordinary "count this thing" answers will be foiled by `NaN != NaN`. – user2357112 Mar 24 '17 at 17:21
  • It turns out they are 'NaN' strings and the list.count('NaN') method works. – Nate Mar 24 '17 at 18:13

1 Answers1

3

You can use collections.Counter:

from collections import Counter

Counter(yourlist)

You will have the number of occurences for every unique value of your list

Another option is:

Use the count method of a list:

yourlist.count('Nan')

LoicM
  • 1,786
  • 16
  • 37
  • 3
    Except that, if those values are actual NaNs (i.e. `float('NaN')`), none of these methods work. – NPE Mar 24 '17 at 17:21
  • Actually... that's right. I hope the answers have a solution that works, otherwise I will try to update mine when I get off work. – LoicM Mar 24 '17 at 17:25
  • 5
    If it's a 'real' NaN: `import math; len([0 for x in your_list if math.isnan(x)])` – Ryan Mar 24 '17 at 17:27
  • 11
    @Ryan I would use `sum(math.isnan(x) for x in your_list)` more memory efficient :) – juanpa.arrivillaga Mar 24 '17 at 17:31
  • This is better! I was considering using sum and forgot that it takes a generator, so I didn't want to iterate twice. Len I believe is constant? – Ryan Mar 24 '17 at 17:36
  • As I've just found out, `math.isnan(x)` doesn't like it if `x` isn't a float type, e.g. None. `x if x is not None else 0` helps in this situation. – Matti Wens Feb 12 '18 at 21:57