嗨,我有以下資料集
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
我想回傳一個沒有 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']]
有任何想法嗎?
uj5u.com熱心網友回復:
因為NaN是字串pd.notna回傳False,如果需要洗掉'NaN's字串使用:
dfd= [[y for y in x if Y != 'NaN'] for x in df.values.tolist()]
如果將NaNs 字串轉換為缺失值:
df = df.replace('NaN', np.nan)
dfd= [[y for y in x if pd.notna(y)] for x in df.values.tolist()]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/414401.html
標籤:
上一篇:如何根據串列中的新行拆分串列
