【问题标题】:Dealing with missing values when converting a list of dictionaries into a dataframe [duplicate]将字典列表转换为数据框时处理缺失值[重复]
【发布时间】:2021-09-09 13:03:26
【问题描述】:

将dictionaries 的list 转换为pandas dataframe 时,有没有办法处理缺失值?有时dictionary 条目的顺序不同,所以我必须分别处理每一列。

这是一个例子:

p = [
 {'c': 53.13,'n': 1,'t': 1575050400000},
 {'t': 1575048600000,'c': 53.11}
  ]

这是我一直在尝试的:

import pandas as pd
df = pd.DataFrame([{
        "c": t["c"],
        "n": t["n"],
        "t": t['t']}
        for t in p])

我得到一个KeyError: 'n',因为在第二个dictionary 中缺少“n”条目。有没有办法在条目丢失时只输入NaN?

【问题讨论】:

    标签: pandas list dataframe dictionary missing-data


    【解决方案1】:

    您可以从 p 实例化一个 DataFrame 作为参数:

    df = pd.DataFrame(p)
    df
    

    输出:

           c    n              t
    0  53.13  1.0  1575050400000
    1  53.11  NaN  1575048600000
    

    【讨论】:

    • 对不起,我删除了我的评论,因为从您的输出中很明显。
    • @helloimgeorgia 是的,有道理 :) 也删除了我的,以避免混淆
    • @helloimgeorgia 实际上,这里甚至不需要from_dict;只使用pd.DataFrame(p) 会做同样的事情;更新了我的答案
    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2020-09-07
    • 2019-10-19
    • 2023-02-02
    相关资源
    最近更新 更多