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
>Solution :
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)