python - 将 JSON 链接转换为 Pandas DataFrame
问题描述
请看下面的问题解释。我有一个 JSON 数据源:https ://data.cdc.gov/api/views/x8jf-txib/rows.json ,我想将此数据转换为 Pandas 数据框。
如果您查看 JSON 数据集,它由元数据和实际数据组成。我想有一种方法可以将元数据存储在不同的文件中,而将数据集存储在本地系统的不同文件中。
我已经开发了这种方法,但我无法让它完全适合我:
from urllib.request import urlopen
import json
# Get the dataset
url = "https://data.cdc.gov/api/views/x8jf-txib/rows.json"
response = urlopen(url)
# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)
上述步骤将 JSON 文件转换为字典,当我尝试使用以下方法将其转换为 Pandas Dataframe 时:
pd.DataFrame([json_obj.items()])
我得到这样的输出:
请帮助我!我很感激。
解决方案
在 Python 中,json.loads
如果正确解析了 JSON 字符串,则返回一个映射/对象。我认为您要构建的DataFrame
内容如下:
df = pd.DataFrame.from_records(json_obj['data'])
这是一个工作脚本:
import pandas as pd
from urllib.request import urlopen
import json
# Get the dataset
url = "https://data.cdc.gov/api/views/x8jf-txib/rows.json"
response = urlopen(url)
# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)
df = pd.DataFrame.from_records(json_obj['data'])
print(df.head())
您应该得到如下所示的输出:
0 1 2 ... 38 39 40
0 row-ss5i~ibqh-im6e 00000000-0000-0000-E6C3-33C094361E41 0 ... None None None
1 row-7jrs-n8wf_crzs 00000000-0000-0000-22EC-13B75E5E7127 0 ... None None None
2 row-ddqq-yzd7.yyhz 00000000-0000-0000-319D-A1D4FB17A377 0 ... None None None
3 row-kzem-t4xs.n4ss 00000000-0000-0000-6ED5-CF3857CC1862 0 ... None None None
4 row-9ws9-2nrx~xqqg 00000000-0000-0000-3403-E46EFF15AE5B 0 ... POINT (-89.148632 40.124144) 1721 34
推荐阅读
- amazon-s3 - Kafka S3 源连接器
- python - 我的 on_message 功能不再起作用
- elasticsearch - Elasticsearch 未在云 URL 中打开
- php - 如何在docker容器中访问主机的mongo db
- python - 将 pandas df 转换为嵌套字典
- angular - 使用角度重定向问题的 Microsoft 多因素身份验证
- javascript - 如何通过特定索引获取未来的项目和过去的项目,比如在轮播中
- javascript - 尝试解决 N Rook 问题时遇到问题。总是得到 n*n 解而不是 N 阶乘
- html - 在不同的缩放级别上保持 css 右箭头的大小相同
- mysql - 续集插入级联