0

Given:

a = [["a","",""],
 ["b","",""],
 ["c","d",""]]

b = [["a", nan, nan],
["b", nan, nan],
["c","d", nan]]

I would like to remove the value which is nan or empty string.

This is my current code:

while("" in a):
    a.remove("")

and

b = [x for x in b if str(x) != nan]

but both don't work, what should I do?

3
  • 1
    nan as in numpy.nan or str ("nan")? Commented Sep 26, 2019 at 2:23
  • a is a list-of-lists. "" is not a direct member of a. Commented Sep 26, 2019 at 2:33
  • @Chris is NaN in the excel before i change it to list ,so I guess is numpy.nan Commented Sep 26, 2019 at 2:46

3 Answers 3

1

Here is the corrected version.

from math import isnan  # numpy.isnan can also be used instead

# If the list contains only strings, `if e != ""` can be simplied to `if e`
a = [[e for e in l if e != ""] for l in a]

# Use isnan function to check for nan values
b = [[e for e in l if not isnan(e)] for l in b]
Sign up to request clarification or add additional context in comments.

Comments

0

x for x in b only looks at list level 1.

Try this:

b = [[n for n in b] for x in b if n not in ('nan', "")]

Comments

0

list.remove("") removes the first "" element in list. a doesn't contain "". You should do it for every sublist in a or b.

for l in a:
    while "" in l:
        l.remove("")    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.