在元组列表中删除包含nan的元组-Python [英] Remove a tuple containing nan in list of tuples -- Python

查看:283
本文介绍了在元组列表中删除包含nan的元组-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很长的元组列表,并且想要使用Python删除其中包含nan的任何元组.

I have a long list of tuples and want to remove any tuple that has a nan in it using Python.

我目前所拥有的: x = [('Recording start',0),(nan,4),(nan,7),...,('事件标记1',150)]

What I currently have: x = [('Recording start', 0), (nan, 4), (nan, 7), ..., ('Event marker 1', 150)]

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

Result I'm looking for: x = [('Recording start', 0), ('Event marker 1', 150)]

我尝试使用np.isnan及其变体,但没有成功,并不断出现错误:输入类型不支持ufunc'isnan',并且不能将输入安全地强制为任何受支持的根据强制转换规则安全"进行类型

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"

任何建议将不胜感激!!

Any suggestions would be appreciated!!

推荐答案

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

You could use list comprehension which checks if any of the items in a tuple is NaN. Check is done by first checking the type and then with math.isnan since it doesn't work for other types:

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)]

这篇关于在元组列表中删除包含nan的元组-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆