【问题标题】:Reading Json file and converting it to columns in python读取 Json 文件并将其转换为 python 中的列
【发布时间】:2019-07-08 17:45:29
【问题描述】:

我正在尝试使用此代码在 python 中读取this json file(我希望将所有数据都放在一个数据框中):

import numpy as np
import pandas as pd
import json 
from pandas.io.json import json_normalize

df = pd.read_json('short_desc.json')
df.head()

Data frame head screenshot

使用此代码,我只能将第一行转换为单独的列:

json_normalize(df.short_desc.iloc[0])

First row screenshot

我想用这段代码对整个 df 做同样的事情:

df.apply(lambda x : json_normalize(x.iloc[0]))

但我收到此错误:

ValueError: 如果使用所有标量值,则必须传递索引

我做错了什么?

提前谢谢你

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    json.load读取json文件后,可以使用pd.DataFrame.from_records。这应该会创建您正在寻找的 DataFrame。

    wih open('short_desc.json') as f:
        d = json.load(f)
    
    df = pd.DataFrame.from_records(d)
    

    【讨论】:

    • 它给了我一个包含 Json 列的数据集,我正在尝试将 json 转换为列。看看这个i.stack.imgur.com/aAuY6.png,我想为时间、内容和人员设置单独的列
    • 你的 json 是什么样子的?
    • 如果你想使用json_normalize,请从我上面的回答中通过d。如果没有看到您的 JSON 数据,很难说出发生了什么。
    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 2014-09-16
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多