删除元组列表中包含 nan 的元组 -- Python

Remove a tuple containing nan in list of tuples -- Python

我有一长串元组,想使用 Python 删除其中包含 nan 的任何元组。

我目前拥有的: x = [('Recording start', 0), (nan, 4), (nan, 7), ..., ('Event marker 1', 150)]

我正在寻找的结果: x = [('Recording start', 0), ('Event marker 1', 150)]

我试过使用 np.isnan 及其变体,但没有成功并不断收到错误消息:输入类型不支持 ufunc 'isnan',并且输入无法根据转换规则 "safe"

安全地强制转换为任何受支持的类型

如有任何建议,我们将不胜感激!!

res = [n for n in x if not nan in n]

Return x 中没有对象 nan 的所有对象。

使用列表理解:

x = [('Recording start', 0), (nan, 4), (nan, 7), ('Event marker 1', 150)]

new = [i for i in x if nan not in i]

您可以使用列表理解来检查元组中的任何项目是否为 NaN。检查是通过首先检查类型然后使用 math.isnan 完成的,因为它不适用于其他类型:

import math

x = [('Recording start', 0), (float('nan'), 4), (float('nan'), 7), ('Event marker 1', 150)]
res = [t for t in x if not any(isinstance(n, float) and math.isnan(n) for n in t)]
print(res)

输出:

[('Recording start', 0), ('Event marker 1', 150)]

至少在我 python 的 nan 用法中返回了 'not defined error',这就是我自己定义它的原因。 我认为您可以根据需要使用 Python 过滤功能。看例子:

nan = float('nan')
lst = [('Recording start', 0), (nan, 4), (nan, 7), ('Event marker 1', 150)]
y = filter( lambda x: nan not in x, lst)
print y

[('Recording start', 0), ('Event marker 1', 150)]