在pandas read_json中解析json值

问题描述 投票:1回答:1

我正在读取一个json文件来获取数据。 json开头是这样的:

{
"rows": [
    [
        2013,
        "Mazda",
        "3",
        "917723",
        7795,
        20895
    ],
    [
        2016,
        "Cadillac",
        "ATS",
        "DD16135D",
        54890,
        66000
    ]

我试图将连续的值放入单独的列中。我尝试过以下操作:

df = pd.read_json(path, orient='values')

得到了结果:

    rows
0  [2013, Mazda, 3, 917723, 77...
1  [2016, Cadillac, ATS, DD161...
2  [2015, Mitsubishi, Outlander,...
3  [2016, BMW, 528I, 918058, 3...
4  [2015, Toyota, Venza, 91806...

最后,我希望在我的数据框中有7列,每列代表一行中的每个项目。我怎样才能做到这一点?

python json pandas dictionary dataframe
1个回答
2
投票

您可以将json文件读入字典并选择'rows'密钥:

# replace data with open('data.json')
with data as f:
    df = pd.DataFrame(json.load(f)['rows'])

print(df)

      0         1    2         3      4      5
0  2013     Mazda    3    917723   7795  20895
1  2016  Cadillac  ATS  DD16135D  54890  66000

建立

from io import StringIO
import json

data = StringIO("""{
"rows": [
    [
        2013,
        "Mazda",
        "3",
        "917723",
        7795,
        20895
    ],
    [
        2016,
        "Cadillac",
        "ATS",
        "DD16135D",
        54890,
        66000
    ]]}""")
© www.soinside.com 2019 - 2024. All rights reserved.