【问题标题】:transform a dataframe to list ans delete NaN values转换数据框以列出和删除 NaN 值
【发布时间】:2022-01-18 12:44:42
【问题描述】:

嗨,我有以下数据集

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

有什么想法吗?

【问题讨论】:

  • 所以你想在结果中列出长度为 1 的列表?

标签: python pandas list dataframe nan


【解决方案1】:

因为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()]

【讨论】:

    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2012-06-07
    • 2021-08-26
    • 1970-01-01
    • 2023-01-28
    相关资源
    最近更新 更多