1

I'm attempting to remove all nan list items from a nested list

l1= 
[['a', 'b', 'c', 'd', 'e', 'f'],
 [1.0, 2.0, 3.0, 4.0, 5.0, nan],
 ['red', 'orange', 'blue', nan, nan, nan]]

I've tried the following

cleanedList = [x for x in l1 if str(x) != 'nan']

However, this returns the same output

rsq1725
  • 75
  • 2
  • hi, perhaps filter the nested list https://stackoverflow.com/questions/3055358/how-to-remove-an-element-from-a-nested-list – jspcal Feb 04 '22 at 06:20
  • You're comparing `nan` (presumably from `numpy`?) with `'nan'` which is a string, so the two will never match and nothing gets filtered out. – Grismar Feb 04 '22 at 06:21
  • 1
    without list comprehension: l1= [['a', 'b', 'c', 'd', 'e', 'f'], [1.0, 2.0, 3.0, 4.0, 5.0, nan], ['red', 'orange', 'blue', nan, nan, nan]] cleanedList = [] for oldList in l1: newList = [] for val in oldList: if val is not nan: newList.append(val) cleanedList.append(newList) print(cleanedList) –  Feb 04 '22 at 06:29

1 Answers1

3

nan is not equal to itself (this goes for float('nan') as well as np.nan). So, we can use filter(), removing elements which are not equal to itself.

l1 = [['a', 'b', 'c', 'd', 'e', 'f'], 
      [1.0, 2.0, 3.0, 4.0, 5.0, nan], 
      ['red', 'orange', 'blue', nan, nan, nan]]

result = [list(filter(lambda x: x == x, inner_list)) for inner_list in l1]

print(result)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33