【问题标题】:Converting a JSON Link into a Pandas DataFrame将 JSON 链接转换为 Pandas DataFrame
【发布时间】:2020-12-04 19:43:11
【问题描述】:

请看下面的问题解释。 我有一个 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()])

我得到这样的输出:

请帮帮我!我很感激。

【问题讨论】:

  • 试试pd.DataFrame(json_obj['data'])

标签: python python-3.x pandas dataframe data-extraction


【解决方案1】:

在 Python 中,如果 JSON 字符串被正确解析,json.loads 会返回一个映射/对象。我认为您要构建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

【讨论】:

  • 您好先生,感谢您的回复。实际上,在发布此问题后,我能够将元数据与实际数据分开,然后将其转换为数据框。我很想知道的是,如果您不想将 JSON 文件保存在本地机器上并直接从网站访问它并将其转换为数据框进行分析,我们如何才能做到这一点。
  • 您必须将数据存储在本地某处才能读取它。这段代码现在的工作方式是在python进程中将数据保存到内存中。
  • 有没有办法直接从网站读取数据而不是保存在本地系统中
猜你喜欢
  • 2017-04-13
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 2017-01-08
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多