【发布时间】:2020-08-21 07:52:55
【问题描述】:
我正在构建一个小程序来绘制一些 API 数据。我已将其设置为提取数据,然后创建一个本地 json,然后我从中创建一个数据框。
有没有办法跳过本地文件并将数据直接拉入数据框?
如您所见,我正在使用的示例是爱尔兰,但我希望最终得到可以引用任何国家/地区的内容,并希望避免创建文件。
# Import the libraries
import requests
import json
from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pandas import Series, DataFrame
# Save the current API call as a JSON file
# countryStatusdDayOne
# 1. Make an API call and store the response.
url = 'https://api.covid19api.com/total/dayone/country/ireland'
data = requests.get(url)
# Store the API response in a variable.
available_data = data.json()
filename = 'data/covid_call__ireland_day_one_workable.json'
with open(filename, 'w') as f:
json.dump(available_data, f, indent=4)
# read the json
ireland = pd.read_json('data/covid_call__ireland_day_one_workable.json')
# create a dataframe
df_ire = pd.DataFrame(ireland)
这对我来说都是全新的,所以任何关于如何格式化或改进我的代码的建议也非常欢迎!
【问题讨论】:
-
我认为没有办法直接将 API 调用修补到 Pandas。唯一的方法是在 API 上执行获取请求,并将 json 传递给
pd.read_json。
标签: python json pandas api dataframe