【问题标题】:pandas read_json gives multiple columns instead of rowspandas read_json 给出多列而不是行
【发布时间】:2018-07-28 08:56:38
【问题描述】:

我正在尝试使用 read_json 将 json 转换为 pandas 数据帧, 但它总是创建额外的列而不是行

json:

'[{"1981121": {"Summary": "Tasa"}}, {"1981123": {"Summary": "This fox only jumps on the top"}}]'

代码:

pd.read_json(json,orient='index')

结果:

                 0                                              1
1981121  {'Summary': 'Tasa'}                                   NaN
1981123         NaN                {'Summary': 'This fox only jumps on the top'}

我尝试了 'orient' arg 的不同值,但它是相同的

我怎样才能以这种方式获取数据帧

               0         
1981121  {'Summary': 'Tasa'}                                           
1981123  {'Summary': 'This fox only jumps on the top'}

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    Pandas 期望每条记录都是一个元组,而不是一个字典。这是使其工作的一种方法:

    items = [next(iter(d.items())) for d in json]
    pd.DataFrame.from_items(items, orient='index', columns=['Summary'])
    

    然后你得到:

                                    Summary
    1981121                            Tasa
    1981123  This fox only jumps on the top
    

    【讨论】:

    • 这正是我所需要的!关于如何改进以获得知识的任何建议,例如知道 pandas 期望是元组?
    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2018-11-06
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多