1

Filter list of tuples. I tried a few things but the didn't work:

    import numpy as np
    import sys
    import math
    #Python Version:  3.8.1 
    ZL = [('2011',np.nan),('2012',np.nan),('2013','B'),('2014','C')]
    #~ Desired output:   [('2013',20),('2014',34)]
    # I tried the following:
    #~ cleanedZL = filter(lambda x:x[1] != np.nan,ZL)   # Does not work
    #~ cleanedZL = filter(lambda x:x[1] != 'nan',ZL)         # Does not work
    #~ cleanedZL = [i for i in ZL if not math.isnan(i[1])]   # Does not work 
    #~ cleanedZL = [i for i in ZL if i[1] != np.nan]      # Does not work 
    cleanedZL = [i for i in ZL if i[1] != 'nan']      # Does not work 
    for a in cleanedZL:
       print (a)
Dan Mašek
  • 17,852
  • 6
  • 57
  • 85
user39678
  • 73
  • 7
  • Does this answer your question? [Why is comparing to nan yields False (Python)?](https://stackoverflow.com/questions/42856485/why-is-comparing-to-nan-yields-false-python) – Georgy Jan 17 '20 at 13:03

2 Answers2

0

Your tries are all close, but your condition is not quite right.

Your main problem is that np.nan != np.nan, so you need another condition for testing. You could for example use np.isnan(), but this will fail if you feed in strings.

What kind of different values are on the second position of your tuples? If there are only either strings or np.nan you could use isinstance(x, str) for your filter:

cleanedZL = [x for x in ZL if isinstance(i[1], str)]
cleanedZL = list(filter(lambda x:isinstance(x[1],str), ZL))

See also this question for maybe a better solution to comparing np.nans

scleronomic
  • 4,392
  • 1
  • 13
  • 43
0

You just need to change your If statement then it will work.

import numpy as np

ZL = [('2011', np.nan), ('2012', np.nan), ('2013', 'B'), ('2014', 'C')]
final = [i for i in ZL if np.nan not in i]
print(final)

Answer :-

[('2013', 'B'), ('2014', 'C')]
ImMJ
  • 206
  • 2
  • 5