转换数据框以列出和删除 NaN 值
transform a dataframe to list ans delete NaN values
嗨,我有以下数据集
df = pd.DataFrame({'fruits': ['orange', 'mango', 'apple', 'grapes', 'NaN', 'mango'],
'price': ['40', '80', 'NaN', '40', '30', '80']
})
fruits price
0 orange 40
1 mango 80
2 apple NaN
3 grapes 40
4 NaN 30
我想要 return 一个没有 NaN 值的列表。所以我使用以下代码:
dfd= [[y for y in x if pd.notna(y)] for x in df.values.tolist()]
但是,NaN 值仍然存在
[['orange', '40'],
['mango', '80'],
['apple', 'NaN'],
['grapes', '40'],
['NaN', '30'],
['mango', '80']]
有什么想法吗?
因为NaN
是字符串pd.notna
returnFalse
,如果需要删除'NaN's
字符串使用:
dfd= [[y for y in x if Y != 'NaN'] for x in df.values.tolist()]
如果将 NaN
s 个字符串转换为缺失值:
df = df.replace('NaN', np.nan)
dfd= [[y for y in x if pd.notna(y)] for x in df.values.tolist()]
嗨,我有以下数据集
df = pd.DataFrame({'fruits': ['orange', 'mango', 'apple', 'grapes', 'NaN', 'mango'],
'price': ['40', '80', 'NaN', '40', '30', '80']
})
fruits price
0 orange 40
1 mango 80
2 apple NaN
3 grapes 40
4 NaN 30
我想要 return 一个没有 NaN 值的列表。所以我使用以下代码:
dfd= [[y for y in x if pd.notna(y)] for x in df.values.tolist()]
但是,NaN 值仍然存在
[['orange', '40'],
['mango', '80'],
['apple', 'NaN'],
['grapes', '40'],
['NaN', '30'],
['mango', '80']]
有什么想法吗?
因为NaN
是字符串pd.notna
returnFalse
,如果需要删除'NaN's
字符串使用:
dfd= [[y for y in x if Y != 'NaN'] for x in df.values.tolist()]
如果将 NaN
s 个字符串转换为缺失值:
df = df.replace('NaN', np.nan)
dfd= [[y for y in x if pd.notna(y)] for x in df.values.tolist()]