【问题标题】:How to convert OrderedDict with tuples to a Pandas Dataframe如何将带有元组的 OrderedDict 转换为 Pandas 数据框
【发布时间】:2022-01-09 01:45:21
【问题描述】:

我有以下 OrderedDict:

OrderedDict(
[
 ("2021-01-01" , {"name" : "John",    "age" : 25}),
 ("2021-05-05" , {"name" : "Max",     "age" : 15}),
 ("2021-09-09" , {"name" : "Michael", "age" : 35})
]
)

我需要将其转换为 Pandas Dataframe,其中每个 dict 中的每个键都是列名,而日期将是 DataFrame 的索引。我怎样才能做到这一点?

预期的结果应该如下:

date 列是此 DataFrame 的索引。

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    我可能已经被打到这里的帖子,但这里是解决方案:

    from collections import OrderedDict
    x1 = OrderedDict(
    [
     ("2021-01-01" , {"name" : "John",    "age" : 25}),
     ("2021-05-05" , {"name" : "Max",     "age" : 15}),
     ("2021-09-09" , {"name" : "Michael", "age" : 35})
    ]
    )
    
    pd.DataFrame.from_dict(x1).T.rename_axis('date').reset_index()
    

    【讨论】:

    • 谢谢你,@Quixotic22 !!真的很感激。
    【解决方案2】:

    我们可以使用 Pandas 的 transpose 方法得到预期的结果:

    >>> df = pd.DataFrame(data, columns=data.keys()).T
    >>> df
                name    age
    2021-01-01  John    25
    2021-05-05  Max     15
    2021-09-09  Michael 35
    

    【讨论】:

    • 谢谢你,@tlentali !!!
    【解决方案3】:

    试试from_dict

    out = pd.DataFrame.from_dict(d, 'index')
    Out[484]: 
                   name  age
    2021-01-01     John   25
    2021-05-05      Max   15
    2021-09-09  Michael   35
    

    【讨论】:

    • 哇,这也很有效!非常感谢@BENY!
    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 2016-03-31
    • 2016-04-20
    • 1970-01-01
    • 2019-12-03
    • 2018-02-01
    • 2021-01-02
    • 2021-10-24
    相关资源
    最近更新 更多