我可以通过一个单条目字典来解析创建一个数据帧吗?



我使用请求运行了一个API。请求在python中,我得到一个单项目字典的输出。是否有一种有效的方法将单个项目解析为数据框架?我希望最终导出为csv。

r = requests.request("GET", url, headers=headers, params=querystring)
x = r.json()
print (type(x)) 

显示类为'dict'类型的x。

当我输出x时,我得到:

{"chart":{"result":[{"meta":{"currency":"USD","symbol":"AAPL","exchangeName":"NMS","instrumentType":"EQUITY","firstTradeDate":345479400,"regularMarketTime":1612451820,"gmtoffset":-18000,"timezone":"EST","exchangeTimezoneName":"America/New_York","regularMarketPrice":135.54,"chartPreviousClose":133.94,"previousClose":133.94,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EST","start":1612429200,"end":1612449000,"gmtoffset":-18000},"regular":{"timezone":"EST","start":1612449000,"end":1612472400,"gmtoffset":-18000},"post":{"timezone":"EST","start":1612472400,"end":1612486800,"gmtoffset":-18000}},"tradingPeriods":[[{"timezone":"EST","start":1612449000,"end":1612472400,"gmtoffset":-18000}]],"dataGranularity":"1m","range":"1d","validRanges":["3mo","5y","6mo","2y","ytd","1y","1d","max","5d","10y","1mo"]},"timestamp":[1612449000,1612449060,1612449120,1612449180,1612449240,1612449300,1612449360,1612449420,1612449480,1612449540,1612449600,1612449660,1612449720,1612449780,1612449840,1612449900,1612449960,1612450020,1612450080,1612450140,1612450200,1612450260,1612450320,1612450380,1612450440,1612450500,1612450560,1612450620,1612450680,1612450740,1612450800,1612450860,1612450920,1612450980,1612451040,1612451100,1612451160,1612451220,1612451280,1612451340,1612451400,1612451460,1612451520,1612451580,1612451640,1612451700,1612451760],"comparisons":[{"symbol":"MSFT","previousClose":243.0,"gmtoffset":-18000,"high":[243.0,243.2,243.06,241.7141,241.5323,241.49,241.89,242.34,242.5507,243.2399,242.72,242.659

您包含的JSON太大且无效。稍微操作一下,就可以使用标准技术将JSON转换为要使用的数据框架。

df = pd.json_normalize(js["chart"]["result"]).explode("comparisons")
df.join(df.comparisons.apply(pd.Series)).explode("high")

最新更新