[英]Remove a tuple containing nan in list of tuples — Python
I have a long list of tuples and want to remove any tuple that has a nan in it using Python. 我有很长的元组列表,并且想要使用Python删除其中包含nan的任何元组。
What I currently have: x = [('Recording start', 0), (nan, 4), (nan, 7), ..., ('Event marker 1', 150)] 我目前所拥有的:x = [('Recording start',0),(nan,4),(nan,7),...,('Event marker 1',150)]
Result I'm looking for: x = [('Recording start', 0), ('Event marker 1', 150)] 我正在寻找的结果:x = [('记录开始',0),('事件标记1',150)]
I've tried use np.isnan and variants of that, but have had no success and keep getting an error: ufunc 'isnan' is not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule "safe" 我尝试使用np.isnan及其变体,但没有成功,并不断出现错误:输入类型不支持ufunc'isnan',并且根据输入,不能安全地将输入强制转换为任何受支持的类型强制转换规则“安全”
Any suggestions would be appreciated!! 任何建议,将不胜感激!!
You could use list comprehension which checks if any of the items in a tuple is NaN. 您可以使用列表推导来检查元组中的任何项目是否为NaN。 Check is done by first checking the type and then with
math.isnan
since it doesn't work for other types: 首先检查类型,然后使用
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)
Output: 输出:
[('Recording start', 0), ('Event marker 1', 150)]
Using list comprehension: 使用列表理解:
x = [('Recording start', 0), (nan, 4), (nan, 7), ('Event marker 1', 150)]
new = [i for i in x if nan not in i]
res = [n for n in x if not nan in n]
返回x
中没有对象nan
所有对象。
At least at my python usage of nan retured the 'not defined error', this is why I defined it by my self. 至少在我使用python编写nan时,reture被定义为“未定义错误”,这就是为什么我自己定义它的原因。 I think you can use a Python filter function for yor needs.
我认为您可以根据需要使用Python过滤器功能。 See the example:
参见示例:
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)]
[('录制开始',0),('事件标记1',150)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.