如何从列表列表中删除Nan's?

时间:2019-06-18 20:20:46

标签: python

我正在尝试从列表列表中删除所有Nan,我的数据如下:

[[1,2,3,nan,nan,nan],[4,5,nan],[9,8,7,6,5,4,3,nan,nan,nan,nan,nan]]

我已经尝试通过此处的答案(How to delete [NaN] from a list of lists?)来做到这一点:

import math
l = [[1,2,3,np.nan,np.nan,np.nan],[4,5,np.nan],[9,8,7,6,5,4,3,np.nan,np.nan,np.nan,np.nan,np.nan]]
[xs for xs in l if not any(math.isnan(x) for x in xs)]

但是它会删除整个列表,而不仅仅是南列表

2 个答案:

答案 0 :(得分:3)

尝试遍历列表并使用numpy的isnan方法构建新列表。

import numpy as np
nan = np.nan
l = [[1,2,3,nan,nan,nan],[4,5,nan],[9,8,7,6,5,4,3, nan, nan, nan, nan, nan]]
[[x for x in y if not np.isnan(x)] for y in l]

答案 1 :(得分:1)

在没有numpy的情况下,使用math模块:

import math
nan = float('nan')
l = [[1,2,3,nan,nan,nan],[4,5,nan],[9,8,7,6,5,4,3,nan,nan,nan,nan,nan]]
l = [[j for j in i if not math.isnan(j)] for i in l]

print(l)

打印:

[[1, 2, 3], [4, 5], [9, 8, 7, 6, 5, 4, 3]]