为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

杨__羊羊 2023-03-22 13:59:10
我正在尝试将此美国人口普查局 api 数据获取请求放入数据框中,并认为它是一个列表列表,但显示为 NoneType。有没有办法将其制作成可以轻松导出到 CSV 文件的数据框?import request# The Basic API Request:# Build base URLHOST = "https://api.census.gov/data"year = "2010"dataset = "dec/sf1"base_url = "/".join([HOST, year, dataset])# Specify Census variables and other predicatesget_vars = ["NAME","P013001","P037001"]predicates = {}predicates["get"] = ",".join(get_vars)predicates["for"] = "state:*"# Execute the request, examine text of response objectdata = 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"]]
查看完整描述

1 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

这data.text是一个字符串,所以你可以通过json解析它,试试这个


import json

import pandas as pd 

data = pd.DataFrame(json.loads(data.text)[1:], columns=['NAME', 'P013001', 'P037001', 'state'])

你会得到类似于下图的东西。

//img1.sycdn.imooc.com//641a99580001e04504840593.jpg

查看完整回答
反对 回复 2023-03-22
  • 1 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信