Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

python 3.x - Can I parse through a single entry dictionary to create a data frame?

I ran an API using requests.request in python, and am getting an output of a single item dictionary. Is there an efficient way to parse the single item into a dataframe? id like to eventually export to csv.

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

print (type(x)) 

shows class is type 'dict' for x.

when I print x I get:

{"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
question from:https://stackoverflow.com/questions/66052269/can-i-parse-through-a-single-entry-dictionary-to-create-a-data-frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The JSON you included is large and invalid. Manipulating it a little then allows standard techniques to turn JSON into a dataframe to be used.

df = pd.json_normalize(js["chart"]["result"]).explode("comparisons")

df.join(df.comparisons.apply(pd.Series)).explode("high")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...