猿问

有没有一种简单的方法可以将此 API get 请求转换为 DataFrame?

我正在尝试将此美国人口普查局 api 数据获取请求放入数据框中,并认为它是一个列表列表,但显示为 NoneType。有没有办法将其制作成可以轻松导出到 CSV 文件的数据框?


import request


# The Basic API Request:


# Build base URL

HOST = "https://api.census.gov/data"

year = "2010"

dataset = "dec/sf1"

base_url = "/".join([HOST, year, dataset])


# Specify Census variables and other predicates

get_vars = ["NAME","P013001","P037001"]

predicates = {}

predicates["get"] = ",".join(get_vars)

predicates["for"] = "state:*"


# Execute the request, examine text of response object

data = requests.get(base_url, params=predicates)

print(data.text)

这确实会产生以下输出:


[["NAME","P013001","P037001","state"],

["Alabama","37.9","3.02","01"],

["Alaska","33.8","3.21","02"],

["Arizona","35.9","3.19","04"],

...

["Wyoming","36.8","2.96","56"],

["Puerto Rico","36.9","3.17","72"]]


杨__羊羊
浏览 80回答 1
1回答

胡说叔叔

这data.text是一个字符串,所以你可以通过json解析它,试试这个import jsonimport pandas as pd data = pd.DataFrame(json.loads(data.text)[1:], columns=['NAME', 'P013001', 'P037001', 'state'])你会得到类似于下图的东西。
随时随地看视频慕课网APP

相关分类

Python
我要回答