【问题标题】:Remove all nan from nested list [duplicate]从嵌套列表中删除所有 nan [重复]
【发布时间】:2022-02-04 14:28:02
【问题描述】:

我正在尝试从嵌套列表中删除所有 nan 列表项

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 = [x for x in l1 if str(x) != 'nan']

但是,这会返回相同的输出

【问题讨论】:

  • 嗨,也许过滤嵌套列表stackoverflow.com/questions/3055358/…
  • 您将nan(可能来自numpy?)与'nan'(这是一个字符串)进行比较,因此两者永远不会匹配并且没有任何内容被过滤掉。
  • 没有列表理解:l1= [['a', 'b', 'c', 'd', 'e', 'f'], [1.0, 2.0, 3.0, 4.0, 5.0, nan], ['red', 'orange', 'blue', nan, nan, nan]] cleanList = [] for oldList in l1: newList = [] for val in oldList: 如果 val 不是 nan: newList .append(val) cleanList.append(newList) print(cleanedList)

标签: python


【解决方案1】:

nan 不等于它自己(这适用于float('nan') 以及np.nan)。所以,我们可以使用filter(),删除不等于自身的元素。

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)

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2022-11-15
    • 2016-10-19
    • 1970-01-01
    • 2023-02-06
    • 2018-10-29
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    相关资源
    最近更新 更多