Remove a tuple containing nan in list of tuples — Python

▼魔方 西西 提交于 2019-12-20 05:13:31

问题


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

What I currently have: 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)]

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!!


回答1:


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)

Output:

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



回答2:


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]



回答3:


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

Return all objects in x that do not have an objects nan in them.




回答4:


At least at my python usage of nan retured the 'not defined error', this is why I defined it by my self. I think you can use a Python filter function for yor needs. 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)]



来源:https://stackoverflow.com/questions/37486938/remove-a-tuple-containing-nan-in-list-of-tuples-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!