我有一个来自Pandas Data框架的列表列表,其中包含nan值。我想删除所有包含任何nan值的列表。然后绘制剩余值。
示例
test = [[1,2],[1,nan],[3,4]]
最终结果
test = [[1,2],[3,4]]
如果可能的话,我也想使用任何绘图方法根据最终结果制作图表。您将以这种方式提供的任何帮助将不胜感激。
对于这个问题引起的困惑,我深表歉意,列表的列表取自熊猫数据框,因此示例中为什么存在nan。我想保持数据框架不变,并希望使用列表列表
答案 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()
示例图片如下
答案 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]