如何从 Python/NumPy 列表中删除 Nan

新手上路,请多包涵

我有一个计算值的列表,我得到的值之一是“nan”

 countries= [nan, 'USA', 'UK', 'France']

我试图删除它,但每次都会出错

cleanedList = [x for x in countries if (math.isnan(x) == True)]
TypeError: a float is required

当我尝试这个时:

 cleanedList = cities[np.logical_not(np.isnan(countries))]
cleanedList = cities[~np.isnan(countries)]

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

原文由 user3001937 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 245
1 个回答

问题变了,答案也变了:

不能使用 math.isnan 测试字符串,因为它需要一个浮点参数。在您的 countries 列表中,您有浮点数和字符串。

在您的情况下,以下内容就足够了:

 cleanedList = [x for x in countries if str(x) != 'nan']


旧答案

在你的 countries 列表中,文字 'nan' 是一个字符串而不是Python浮点数 nan 相当于:—

 float('NaN')

在您的情况下,以下内容就足够了:

 cleanedList = [x for x in countries if x != 'nan']

原文由 user764357 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题