Python 将API输出转换为数据帧时出现问题
我有以下格式的API输出Python 将API输出转换为数据帧时出现问题,python,json,python-3.x,pandas,dataframe,Python,Json,Python 3.x,Pandas,Dataframe,我有以下格式的API输出 reponse.text '{"position": {"lat": 1.352083, "lon": 103.819836}, "mapView": {"N": 1.4784001, "E": 104.0945001, "S": 1.1496, "W": 103.594}}\n' 我想将此输出转换为数据帧 我的代码 import json d = json.loads(response.text) df = pd.DataFrame(d) 电流输出 po
reponse.text
'{"position": {"lat": 1.352083, "lon": 103.819836}, "mapView": {"N": 1.4784001, "E": 104.0945001, "S": 1.1496, "W": 103.594}}\n'
我想将此输出转换为数据帧
我的代码
import json
d = json.loads(response.text)
df = pd.DataFrame(d)
电流输出
position mapView
E NaN 104.0945
N NaN 1.4784
S NaN 1.1496
W NaN 103.5940
lat 1.352083 NaN
lon 103.819836 NaN
lat lon
1.352083 103.819836
我的预期产出
position mapView
E NaN 104.0945
N NaN 1.4784
S NaN 1.1496
W NaN 103.5940
lat 1.352083 NaN
lon 103.819836 NaN
lat lon
1.352083 103.819836
在python中如何实现这一点?您已经非常接近了。从pandas导入
json\u normalize
,然后您可以简单地使用
from pandas.io.json import json_normalize
jsonData = json.loads(response.text)
df = json_normalize(jsonData)
打印(df)
然后简单地删除额外的列并正确地重命名它 你们非常接近。从pandas导入
json\u normalize
,然后您可以简单地使用
from pandas.io.json import json_normalize
jsonData = json.loads(response.text)
df = json_normalize(jsonData)
import pandas as pd
import json
d = json.loads(response.text)
df =pd.DataFrame([d['position']])
打印(df)
然后简单地删除额外的列并正确地重命名它
import pandas as pd
import json
d = json.loads(response.text)
df =pd.DataFrame([d['position']])
您正在将json解析器创建的整个字典作为参数传递,而您只想使用position键 请查看DataFrame构造函数文档页面以了解其他参数
>>> import pandas as pd
>>> import json
>>> api_resp = json.loads('{"position": {"lat": 1.352083, "lon": 103.819836}, "mapView": {"N": 1.4784001, "E": 104.0945001, "S": 1.1496, "W": 103.594}}\n')
>>> api_resp
{'position': {'lat': 1.352083, 'lon': 103.819836}, 'mapView': {'N': 1.4784001, 'E': 104.0945001, 'S': 1.1496, 'W': 103.594}}
>>> df = pd.DataFrame(data=api_resp['position'], index=[0])
>>> df
lat lon
0 1.352083 103.819836
您将json解析器创建的整个字典作为参数传递,而您只想使用position键 请查看DataFrame构造函数文档页面以了解其他参数
>>> import pandas as pd
>>> import json
>>> api_resp = json.loads('{"position": {"lat": 1.352083, "lon": 103.819836}, "mapView": {"N": 1.4784001, "E": 104.0945001, "S": 1.1496, "W": 103.594}}\n')
>>> api_resp
{'position': {'lat': 1.352083, 'lon': 103.819836}, 'mapView': {'N': 1.4784001, 'E': 104.0945001, 'S': 1.1496, 'W': 103.594}}
>>> df = pd.DataFrame(data=api_resp['position'], index=[0])
>>> df
lat lon
0 1.352083 103.819836