【问题标题】:Convert Json data to Python DataFrame将 Json 数据转换为 Python DataFrame
【发布时间】:2015-07-24 17:45:00
【问题描述】:

这是我第一次访问 API / 使用 json 数据,所以如果有人能指出我了解如何使用它的好资源,我将非常感激。

具体来说,我有这种形式的 json 数据:

{"result": { "code": "OK", "msg": "" },"report_name":"DAILY","columns":["ad","ad_impressions","cpm_cost_per_ad","cost"],"data":[{"row":["CP_CARS10_LR_774470","966","6.002019","5.797950"]}],"total":["966","6.002019","5.797950"],"row_count":1}

我了解这种结构,但我不知道如何将其正确放入 DataFrame。

【问题讨论】:

  • 能否请您发布整个 JSON。
  • 您最好自己解析列名和数据并创建数据框,而不是使用 pd.read_json 类。所以分别解析出列和行的 json['columns'] 和 json['data'][0]['row'] ,然后像往常一样构造你的数据框。

标签: python json pandas


【解决方案1】:

查看您的json 的结构,大概您的数据会有几行,我认为自己构建数据框会更有意义。

此代码使用columns 和data 构建数据框:

In [12]:

import json
import pandas as pd
​
with open('... path to your json file ...') as fp:
    for line in fp:
        obj = json.loads(line)
        columns = obj['columns']
        data = obj['data']
        l = []
        for d in data:
            l += [d['row']]
        df = pd.DataFrame(l, index=None, columns=columns)

df
Out[12]:
ad  ad_impressions  cpm_cost_per_ad cost
0   CP_CARS10_LR_774470 966 6.002019    5.797950

至于其余数据,在您的json 中,我想您可以例如使用总数来检查您的数据框,

In [14]:

sums = df.sum(axis=0)
obj['total']
for i in range(0,3):
    if (obj['total'][i] != sums[i+1]):
        print "error in total"

In [15]:

if obj['row_count'] != len(df.index):
    print "error in row count"

至于json中的其余数据,我很难知道是否应该做其他事情。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    查看熊猫文档。具体来说,

    http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html

    Pandas 支持读取 json 到数据帧

    【讨论】:

    • 我收到一个 pd.read_json(response) 错误,指出“数组必须都是相同的长度”。问题是最后一行“总计”不包括广告名称,我没有从上面的链接中看到任何有关如何处理此问题的文档
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2021-03-26
    • 2022-01-12
    • 2017-09-10
    • 2017-07-20
    • 2021-05-17
    • 2020-12-21
    • 2018-03-11
    相关资源
    最近更新 更多