[英]Importing Json File URL to pandas data frame
I am trying to import as a dataframe a URL that has a JSON file in it.我正在尝试将其中包含 JSON 文件的 URL 作为数据框导入。
import urllib.request, json
import pandas as pd
with urllib.request.urlopen("https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter") as url:
data = json.loads(url.read().decode())
df = pd.DataFrame(data)
print(df)
It is not considering each metric in the JSON file as a column, but puts all the metrics under one column called "metrics"它没有将 JSON 文件中的每个指标视为一列,而是将所有指标放在一个称为“指标”的列下
while the output I am expecting is而我期待的输出是
Let's try this a couple of other ways让我们尝试其他几种方法
Option 1 using pd.read_json
:选项 1 使用
pd.read_json
:
pd.concat([pd.DataFrame(i, index=[0])
for i in
pd.read_json('https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter')['metrics']],
ignore_index=True)
Option 2 using requests
:使用
requests
的选项 2:
import requests
resp = requests.get('https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter')
txt = resp.json()
pd.DataFrame(txt['metrics'])
You can try this:你可以试试这个:
import urllib.request, json
import pandas as pd
from pandas.io.json import json_normalize
with urllib.request.urlopen('https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter') as url:
data = json.loads(url.read().decode())
df = pd.DataFrame(json_normalize(data, 'metrics'))
print(df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.