我正在尝试将 json 文件加载到 Pandas 数据框。我发现有一些嵌套的json。下面是示例 json:
{'events': [{'id': 142896214,
'playerId': 37831,
'teamId': 3157,
'matchId': 2214569,
'matchPeriod': '1H',
'eventSec': 0.8935539999999946,
'eventId': 8,
'eventName': 'Pass',
'subEventId': 85,
'subEventName': 'Simple pass',
'positions': [{'x': 51, 'y': 49}, {'x': 40, 'y': 53}],
'tags': [{'id': 1801, 'tag': {'label': 'accurate'}}]}
Run Code Online (Sandbox Code Playgroud)
我使用以下代码将 json 加载到数据帧中:
with open('EVENTS.json') as f:
jsonstr = json.load(f)
df = pd.io.json.json_normalize(jsonstr['events'])
Run Code Online (Sandbox Code Playgroud)
下面是 df.head() 的输出
但是我发现了两个嵌套的列,例如位置和标签。
我尝试使用以下代码将其展平:
Position_data = json_normalize(data =jsonstr['events'], record_path='positions', meta = ['x','y','x','y'] )
Run Code Online (Sandbox Code Playgroud)
它向我显示了如下错误:
KeyError: "Try running with errors='ignore' as key 'x' is …Run Code Online (Sandbox Code Playgroud) 希望提高我的数据科学技能。我正在练习从体育网站拉取 url 数据,并且 json 文件有多个嵌套字典。我希望能够提取这些数据以在 matplotlib 等中映射我自己的排行榜的自定义形式,但是我很难将 json 转换为可行的 df。
主要网站为:https : //www.usopen.com/scoring.html
看看背景,我相信实时信息是从下面短代码中列出的链接中提取的。我正在使用 Jupyter 笔记本。我可以成功拉取数据。
但是正如您所看到的,它正在提取多个嵌套字典,这使得提取简单的数据帧变得非常困难。
只是想得到球员,比分达到标准杆,总分和回合拉。任何帮助将不胜感激,谢谢!
import pandas as pd
import urllib as ul
import json
url = "https://gripapi-static-pd.usopen.com/gripapi/leaderboard.json"
response = ul.request.urlopen(url)
data = json.loads(response.read())
print(data)
Run Code Online (Sandbox Code Playgroud) 我用来pd.json_normalize将"sections"这些数据中的字段展平为行。除了空列表的行之外,它工作正常"sections"。
该 ID 被完全忽略,并且从最终的扁平化数据框中丢失。我需要确保数据中的每个唯一 ID 至少有一行(某些 ID 可能有很多行,每个唯一 ID、每个唯一 、section_id、question_id以及answer_id当我在数据中取消嵌套更多字段时最多可以有一行):
{'_id': '5f48f708fe22ca4d15fb3b55',
'created_at': '2020-08-28T12:22:32Z',
'sections': []}]
Run Code Online (Sandbox Code Playgroud)
样本数据:
sample = [{'_id': '5f48bee4c54cf6b5e8048274',
'created_at': '2020-08-28T08:23:00Z',
'sections': [{'comment': '',
'type_fail': None,
'answers': [{'comment': 'stuff',
'feedback': [],
'value': 10.0,
'answer_type': 'default',
'question_id': '5e59599c68369c24069630fd',
'answer_id': '5e595a7c3fbb70448b6ff935'},
{'comment': 'stuff',
'feedback': [],
'value': 10.0,
'answer_type': 'default',
'question_id': '5e598939cedcaf5b865ef99a',
'answer_id': '5e598939cedcaf5b865ef998'}],
'score': 20.0,
'passed': True,
'_id': '5e59599c68369c24069630fe',
'custom_fields': []},
{'comment': '',
'type_fail': None,
'answers': [{'comment': '', …Run Code Online (Sandbox Code Playgroud) 我有一个名为 json 变量,json_results并且正在运行pandas.json_normalize(json_results). 它会引发以下错误:
in _json_normalize
raise NotImplementedError
NotImplementedError
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
我需要做一个python脚本来
person_id, name, flag)的 csv 文件。该文件有 3000 行。person_id来自 csv 文件,我需要调用一个 URL 传递person_idGET
http://api.myendpoint.intranet/get-data/1234
该 URL 将返回 的一些信息person_id,如下例所示。我需要获取所有租金对象并保存在我的 csv 中。我的输出需要是这样的import pandas as pd
import requests
ids = pd.read_csv(f"{path}/data.csv", delimiter=';')
person_rents = df = pd.DataFrame([], columns=list('person_id','carId','price','rentStatus'))
for id in ids:
response = request.get(f'endpoint/{id["person_id"]}')
json = response.json()
person_rents.append( [person_id, rent['carId'], rent['price'], rent['rentStatus'] ] )
pd.read_csv(f"{path}/data.csv", delimiter=';' )
Run Code Online (Sandbox Code Playgroud)
person_id;name;flag;cardId;price;rentStatus
1000;Joseph;1;6638;1000;active
1000;Joseph;1;5566;2000;active
Run Code Online (Sandbox Code Playgroud)
响应示例
{
"active": false,
"ctodx": false,
"rents": [{
"carId": 6638, …Run Code Online (Sandbox Code Playgroud) 我正在尝试扩展 pandas 数据框中的嵌套 json 数组。
\n这就是我的 JSON:
\n[ {\n "id": "0001",\n "name": "Stiven",\n "location": [{\n "country": "Colombia",\n "department": "Choc\xc3\xb3",\n "city": "Quibd\xc3\xb3"\n }, {\n "country": "Colombia",\n "department": "Antioquia",\n "city": "Medellin"\n }, {\n "country": "Colombia",\n "department": "Cundinamarca",\n "city": "Bogot\xc3\xa1"\n }\n ]\n }, {\n "id": "0002",\n "name": "Jhon Jaime",\n "location": [{\n "country": "Colombia",\n "department": "Valle del Cauca",\n "city": "Cali"\n }, {\n "country": "Colombia",\n "department": "Putumayo",\n "city": "Mocoa"\n }, {\n "country": "Colombia",\n "department": "Arauca",\n "city": "Arauca"\n }\n ]\n }, {\n "id": "0003",\n …Run Code Online (Sandbox Code Playgroud) pandas.DataFramestr、dict或listtype。NaN时处理值的问题。df.dropna().reset_index(drop=True)str必须将列中的值转换为dict类型,使用, 。ast.literal_eval.json_normalizeimport numpy as np
import pandas as pd
from ast import literal_eval
df = pd.DataFrame({'col_str': ['{"a": "46", "b": "3", "c": "12"}', '{"b": "2", "c": "7"}', '{"c": "11"}', np.NaN]})
col_str
0 {"a": "46", "b": "3", "c": "12"}
1 {"b": "2", "c": "7"}
2 {"c": "11"}
3 NaN
type(df.iloc[0, 0])
[out]: str
df.col_str.apply(literal_eval)
Run Code Online (Sandbox Code Playgroud)
错误:
df.col_str.apply(literal_eval) results in ValueError: malformed …Run Code Online (Sandbox Code Playgroud) 我正在尝试转换包含其他数据帧的数据帧,例如:
{
'id': 3241234,
'data': {
'name':'carol',
'lastname': 'netflik',
'office': {
'num': 3543,
'department': 'trigy'
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用:
pd.DataFrame.from_dict(data)
Run Code Online (Sandbox Code Playgroud)
但结果数据框如下所示:
id data
lastname 3241234 netflik
name 3241234 carol
office 3241234 {'num': 3543, 'department': 'trigy'}
Run Code Online (Sandbox Code Playgroud)
任何想法?
这是我的简单示例(我的实际数据集中的 json 字段非常嵌套,因此我一次解压一层)。我需要在 json_normalize() 之后保留数据集上的某些列。
https://pandas.pydata.org/docs/reference/api/pandas.json_normalize.html
import json
d = {'report_id': [100, 101, 102], 'start_date': ["2021-03-12", "2021-04-22", "2021-05-02"],
'report_json': ['{"name":"John", "age":30, "disease":"A-Pox"}', '{"name":"Mary", "age":22, "disease":"B-Pox"}', '{"name":"Karen", "age":42, "disease":"C-Pox"}']}
df = pd.DataFrame(data=d)
display(df)
df = pd.json_normalize(df['report_json'].apply(json.loads), max_level=0, meta=['report_id', 'start_date'])
display(df)
Run Code Online (Sandbox Code Playgroud)
查看 json_normalize() 的文档,我认为元参数是我需要保留 report_id 和 start_date 的参数,但它似乎不起作用,因为要保留的预期字段没有出现在最终数据集上。
有人有建议吗?谢谢。
我知道关于将 JSON 文件转换为 pandas df 有一些问题,但没有任何效果。具体来说,JSON 请求当前日期信息。我试图返回对应的表格结构,Data但我只得到第一个dict对象。
我将在下面列出当前的尝试和结果输出。
import requests
import pandas as pd
import json
get_session_url = "https://qships.tmr.qld.gov.au/webx/"
get_data_url = "https://qships.tmr.qld.gov.au/webx/services/wxdata.svc/GetDataX"
get_data_query = {
"token": None,
"reportCode": "MSQ-WEB-0001",
"dataSource": None,
"filterName": "Today",
"parameters": [{
"__type": "ParameterValueDTO:#WebX.Core.DTO",
"sName": "DOMAIN_ID",
"iValueType": 0,
"aoValues": [{"Value": -1}],
}],
"metaVersion": 0,
}
sess = requests.session()
sess.get(get_session_url).raise_for_status()
my_dict = sess.post(get_data_url, json = get_data_query).json()
print(my_dict)
Run Code Online (Sandbox Code Playgroud)
输出:
{'d': {'__type': 'DataSetDTO:#WebX.Core.DTO', 'BuildVersion': '7.0.0.12590', 'ReportCode': 'MSQ-WEB-0001', 'Tables': [{'__type': 'DataTableDTO:#WebX.Core.DTO', 'BuildVersion': '7.0.0.12590', 'AsOfDate': '14:36 on Jan …Run Code Online (Sandbox Code Playgroud) json-normalize ×10
pandas ×9
python ×9
json ×7
dictionary ×3
dataframe ×2
python-3.x ×2
flatten ×1