gpt4 book ai didi

python - 如何将 pandas DataFrame 转换为省略 NaN 值的字典列表?

转载 作者:行者123 更新时间:2023-11-28 21:38:54 27 4
gpt4 key购买 nike

这个问题类似于Pandas DataFrame to List of Dictionaries ,除了 DataFrame 不是“完整的”:其中有一些 nan 值。假设我从字典列表中生成一个 DataFrame,如下所示:

import pandas as pd

data = [{'foo': 1, 'bar': 2}, {'foo': 3}]
df = pd.DataFrame(data)

因此生成的 df 看起来像

   bar  foo
0 2.0 1
1 NaN 3

我想要一个将 df 变回原始 data 字典列表的函数。不幸的是,

assert df.to_dict('records') == data

失败是因为前者是

[{'bar': 2.0, 'foo': 1.0}, {'bar': nan, 'foo': 3.0}]

在第二项中使用额外的 'bar': nan 键值对。我怎样才能取回原始的数据

最佳答案

还有另一种方法:

df.T.apply(lambda x: x.dropna().to_dict()).tolist()

输出:

[{'bar': 2.0, 'foo': 1.0}, {'foo': 3.0}]

关于python - 如何将 pandas DataFrame 转换为省略 NaN 值的字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544088/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com