首页 > 解决方案 > 将 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()])

我得到这样的输出:

在此处输入图像描述

请帮助我!我很感激。

标签: pythonpython-3.xpandasdataframedata-extraction

解决方案


在 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

推荐阅读