在lis中删除'NaN'和单个报价项

2024-09-20 03:59:28 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是在列表中删除“NaN”和单个报价项。我正在使用numpy,但它不起作用。你知道吗

输入:

abc=[['mai', 'dubai', '200ml', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN'],
     ['nestle', '', 'nido', 'milk', 'powder', '', '2.5kg', '(n1)', 'NaN'],
     ['al', 'alali', 'mushroom', 'pieces', '&', 'stems', '400gm', 'NaN', 'NaN'],
     ['mai', 'dubai', 'cup', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN']]


x = abc[~np.isnan(abc)]


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

预期输出:

abc=[['mai', 'dubai', '200ml'],
     ['nestle', 'nido', 'milk', 'powder', '2.5kg', '(n1)'],
     ['al', 'alali', 'mushroom', 'pieces', 'stems', '400gm'],
     ['mai', 'dubai', 'cup']]

谢谢


Tags: thenanalabckgmilkmain1
2条回答

不使用numpy,您可以使用列表理解和filter

exclude = ('', 'NaN')
[list(filter(lambda x: x not in exclude, l)) for l in abc]

我想你可以做一个简单的列表理解。你知道吗

result = [[i for i in x if i != 'NaN' and i != ''] for x in abc]

[['mai', 'dubai', '200ml'],
 ['nestle', 'nido', 'milk', 'powder', '2.5kg', '(n1)'],
 ['mai', 'dubai', 'cup']]

相关问题 更多 >