python - 如何从包含字符串条目的列表列表中删除 NaN?

标签 python list

我正在尝试从列表列表(带有字符串条目)中删除所有 nans,我的数据如下:

[['beer', 'nuts', nan], 
['beer', 'butter', 'apple'], 
['beer', 'nuts', 'cheese'], 
['beer', 'bananas', nan], 
['beer', 'nuts', 'apple']]

我想得到这个结果:

[['beer', 'nuts'], 
['beer', 'butter', 'apple'], 
['beer', 'nuts', 'cheese'], 
['beer', 'bananas'], 
['beer', 'nuts', 'apple']]

我试过从(How to remove nan's from list of lists? [duplicate] How to delete [NaN] from a list of lists?)中得到答案,即:

import math
nan = float('nan')

store_data_list = [[x for x in y if not math.isnan(x)] for y in store_data_list] #remove nans from list of lists

#AND

store_data_list = [xs for xs in store_data_list if not any(math.isnan(x) for x in xs)]

#AND

store_data_list = [[x for x in y if not np.isnan(x)] for y in store_data_list]

两者在我的实例中似乎都不起作用。我收到错误:

TypeError: must be real number, not str

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

谁能指出我做错了什么

最佳答案

一种选择是将项目与其自身进行比较(这对于 nan 是错误的)

nan = float('nan')
data = [['beer', 'nuts', nan], 
        ['beer', 'butter', 'apple'], 
        ['beer', 'nuts', 'cheese'], 
        ['beer', 'bananas', nan], 
        ['beer', 'nuts', 'apple']]
[[i for i in j if i == i] for j in data]

给予

[['beer', 'nuts'],
 ['beer', 'butter', 'apple'],
 ['beer', 'nuts', 'cheese'],
 ['beer', 'bananas'],
 ['beer', 'nuts', 'apple']]

关于python - 如何从包含字符串条目的列表列表中删除 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57790623/

相关文章:

python - 如何以通用换行模式访问上传的文件?

python - 如何检查数据框中的文本列是否包含可能的模式列表,从而允许错误输入?

python - 导入 Word2Vec 模型时出现 Gensim 错误

html - 如何在右侧列出图标并在每个图标下方相应地显示文字?

python - Tkinter TTK 按钮粗体字体

python - 遍历关于嵌套字典的字典

C# sp2010 向列表中添加项目

r - 在 R 中将列表列表转换为 data.frame

python - 使用 csv 模块将列表元素写入 python 中的 csv 文件中的字段

python - 如何使用列表理解从列表中返回元组和计数