如何将嵌套JSON转换为数据帧

2024-09-24 02:25:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下嵌套的json:

import requests

    headers = {
        'Content-Type': 'application/json'
    }
    r = requests.get("...API DATA...")
    [
        {
            "ticker":"btcusd",
            "baseCurrency":"btc",
            "quoteCurrency":"usd",
            "priceData":[
                {
                    "open":3914.749407813885,
                    "high":3942.374263716895,
                    "low":3846.1755315352952,
                    "close":3849.1217299601617,
                    "date":"2019-01-02T00:00:00+00:00",
                    "tradesDone":756.0,
                    "volume":339.68131616889997,
                    "volumeNotional":1307474.735327181
                }
            ]
        }
    ]

我想把它转换成熊猫数据帧。我已经能够做到这一点:

j = r.json()
df = pd.DataFrame.from_dict(j)
df

输出:

output

我还想在列中展开“priceData”

我尝试了不同的方法,包括json.normalise和json.loads,但总有一个错误我无法理解

谁能告诉我怎么做才能理解吗

谢谢

编辑

priceData包含多个元素

数据帧中基本上不需要“ticker”、“baseCurrency”和“quoteCurrency”,因此可以丢弃

part of json elements


Tags: 数据importapijsondfgetapplicationtype
1条回答
网友
1楼 · 发布于 2024-09-24 02:25:55

使用json_normalize

import pandas as pd
pd.json_normalize(data,'priceData',['ticker','baseCurrency','quoteCurrency'])

在哪里,

data = [
    {
        "ticker":"btcusd",
        "baseCurrency":"btc",
        "quoteCurrency":"usd",
        "priceData":[
            {
                "open":3914.749407813885,
                "high":3942.374263716895,
                "low":3846.1755315352952,
                "close":3849.1217299601617,
                "date":"2019-01-02T00:00:00+00:00",
                "tradesDone":756.0,
                "volume":339.68131616889997,
                "volumeNotional":1307474.735327181
            }
        ]
    }
]

编辑:用于多个API调用

final_data = []
for _ in range(3): ## how ever many times you want to call the API
    ## get you data from each API call
    final_data.extend(data)

相关问题 更多 >