如果 nan 在列表的列表中,则删除列表
Remove list if nan is in a lists of lists
我有一个来自 Pandas 数据框的列表列表,其中包含 nan 值。我想删除所有包含任何 nan 值的列表。然后绘制剩余的值。
示例
test = [[1,2],[1,nan],[3,4]]
最终结果
test = [[1,2],[3,4]]
如果可能的话,我还想使用任何绘图方法根据最终结果制作图表。如果您能就此方式提供任何帮助,我们将不胜感激。
对于这个问题造成的混乱,我深表歉意,列表列表取自 pandas 数据框,因此示例中出现了 nan。我想保持数据框不变,并希望使用列表列表
正在从列表中删除值
使用filter
nan
不是正确的 Python 语法,仅在 Pandas
库中使用。所以我打算用 None
.
替换这个值
我们可以使用 filter
函数删除列表中包含 nan
值的任何值。
test = list(filter(lambda x: None not in x, test))
使用列表理解
编辑:应该是 x
而不是 test
。谢谢@fountainhead
test = [x for x in test if None not in test]
test = [x for x in test if None not in x]
两者都会 return 一个列表,其中的值不包含 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()
示例图片如下
你可以re-construct你的列表使用列表理解,没有 sub-lists 有 nans:
import math
test = [sub_list for sub_list in test if not any(math.isnan(x) for x in sub_list)]
如果您想从 test
列表 'in-place' 中删除,您可以这样做:
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]
我有一个来自 Pandas 数据框的列表列表,其中包含 nan 值。我想删除所有包含任何 nan 值的列表。然后绘制剩余的值。
示例
test = [[1,2],[1,nan],[3,4]]
最终结果
test = [[1,2],[3,4]]
如果可能的话,我还想使用任何绘图方法根据最终结果制作图表。如果您能就此方式提供任何帮助,我们将不胜感激。
对于这个问题造成的混乱,我深表歉意,列表列表取自 pandas 数据框,因此示例中出现了 nan。我想保持数据框不变,并希望使用列表列表
正在从列表中删除值
使用filter
nan
不是正确的 Python 语法,仅在 Pandas
库中使用。所以我打算用 None
.
我们可以使用 filter
函数删除列表中包含 nan
值的任何值。
test = list(filter(lambda x: None not in x, test))
使用列表理解
编辑:应该是 x
而不是 test
。谢谢@fountainhead
test = [x for x in test if None not in test]
test = [x for x in test if None not in x]
两者都会 return 一个列表,其中的值不包含 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()
示例图片如下
你可以re-construct你的列表使用列表理解,没有 sub-lists 有 nans:
import math
test = [sub_list for sub_list in test if not any(math.isnan(x) for x in sub_list)]
如果您想从 test
列表 'in-place' 中删除,您可以这样做:
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]