gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:29 24 4
gpt4 key购买 nike

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

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

我正在寻找的结果: x = [('记录开始', 0), ('事件标记 1', 150)]

我试过使用 np.isnan 和它的变体,但没有成功并不断收到错误:ufunc 'isnan' is not supported for the input types, and the inputs could not be safely coerced to any supported根据类型转换规则“安全”类型

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

最佳答案

您可以使用列表理解来检查元组中的任何项目是否为 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 的元组——Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37486938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com