如果nan在列表列表中,则删除列表

时间:2020-11-06 18:02:50

标签: python nan nested-lists

我有一个来自Pandas Data框架的列表列表,其中包含nan值。我想删除所有包含任何nan值的列表。然后绘制剩余值。

示例

test = [[1,2],[1,nan],[3,4]]

最终结果

test = [[1,2],[3,4]]

如果可能的话,我也想使用任何绘图方法根据最终结果制作图表。您将以这种方式提供的任何帮助将不胜感激。

对于这个问题引起的困惑,我深表歉意,列表的列表取自熊猫数据框,因此示例中为什么存在nan。我想保持数据框架不变,并希望使用列表列表

2 个答案:

答案 0 :(得分:0)

从列表中删除值

使用filter

nan不是正确的Python语法,仅在Pandas库中使用。因此,我将用None替换此值。

我们可以使用filter函数删除列表中包含nan值的所有值。

test = list(filter(lambda x: None not in x, test))

使用列表理解

编辑:应为x,而不是test。谢谢@fountainhead

test = [如果没有测试,则x表示测试中的x]

test = [x for x in test if None not in x]

两者都会返回一个列表,其中的值中不包含None

绘图

我们可以使用名为matplotlib的库来绘制图形。例如,要创建散点图:

import matplotlib.pyplot as plt
plt.scatter(x, y)

其中plt.scatter分别接受行和列的x值和y值。完整的代码如下:

import matplotlib.pyplot as plt

test = [[1,2],[1,None],[3,4]]
test = list(filter(lambda x: None not in x, test))

x = [x for x,y in test]
y = [y for x,y in test]

# Assume all first elements are x values second elements are y values
plt.scatter(x, y)
plt.show()

示例图片如下

enter image description here

答案 1 :(得分:0)

您可以使用列表理解功能来重新构建列表,而子列表不包含nans:

import math

test = [sub_list for sub_list in test if not any(math.isnan(x) for x in sub_list)]

如果要从“就地” test列表中删除,可以执行以下操作:

import math

for (which, sub_list) in enumerate(test[::-1]):
    if any(math.isnan(x) for x in sub_list):
        del test[len(test)-1-which]