从python中的列表列表中删除值/ nan /空字符串(“”)

时间:2019-09-26 02:21:38

标签: python

给出:

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

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

我想删除nan或空字符串的值。

这是我当前的代码:

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

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

但是两者都不起作用,我该怎么办?

3 个答案:

答案 0 :(得分:1)

这是更正的版本。

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]

答案 1 :(得分:0)

x for x in b仅查看列表级别1。

尝试一下:

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

答案 2 :(得分:0)

list.remove(“”)删除列表中的第一个“”元素。一个不包含“”。您应该对a或b中的每个子列表执行此操作。

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