解析 pandas 中的json值read_json [英] Parsing json values in pandas read_json

查看:131
本文介绍了解析 pandas 中的json值read_json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取json文件以获取数据. json的开头是这样的:

I am reading a json file to get data. The json begins like this:

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

我正在尝试将一行中的值放入单独的列中. 我尝试执行以下操作:

I am trying to get the values in a row into separate columns. I have tried doing the following:

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列,每一列代表一行中的每个项目.我该如何实现?

Ultimately, I would like to have 7 columns in my dataframe, each column representing each item in a row. How can I achieve this?

推荐答案

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

You can read the json file into a dictionary and select the 'rows' key:

# 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
    ]]}""")

这篇关于解析 pandas 中的json值read_json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆