JSON 转 Pandas DataFrame
- 2024-12-03 08:45:00
- admin 原创
- 176
问题描述:
我想要做的是从 Google 地图 API 中沿着经纬度坐标指定的路径提取海拔数据,如下所示:
from urllib2 import Request, urlopen
import json
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
这给了我如下数据:
elevations.splitlines()
['{',
' "results" : [',
' {',
' "elevation" : 243.3462677001953,',
' "location" : {',
' "lat" : 42.974049,',
' "lng" : -81.205203',
' },',
' "resolution" : 19.08790397644043',
' },',
' {',
' "elevation" : 244.1318664550781,',
' "location" : {',
' "lat" : 42.974298,',
' "lng" : -81.19575500000001',
' },',
' "resolution" : 19.08790397644043',
' }',
' ],',
' "status" : "OK"',
'}']
当将其放入 DataFrame 中时,我得到的结果如下:
pd.read_json(elevations)
这就是我想要的:
我不确定这是否可行,但我主要寻找的是一种能够将海拔、纬度和经度数据放在一起放入熊猫数据框中的方法(不必有花哨的多行标题)。
如果有人能帮忙或给出一些关于如何处理这些数据的建议那就太好了!如果你不知道我以前没有处理过 json 数据……
编辑:
这种方法虽然不太有吸引力,但似乎有效:
data = json.loads(elevations)
lat,lng,el = [],[],[]
for result in data['results']:
lat.append(result[u'location'][u'lat'])
lng.append(result[u'location'][u'lng'])
el.append(result[u'elevation'])
df = pd.DataFrame([lat,lng,el]).T
最终数据框包含纬度、经度、海拔等列
解决方案 1:
我找到了一个快速简便的解决方案,可以使用json_normalize()
包含在其中的内容pandas 1.01
。
from urllib2 import Request, urlopen
import json
import pandas as pd
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
data = json.loads(elevations)
df = pd.json_normalize(data['results'])
这给出了一个很好的扁平数据框,其中包含我从 Google Maps API 获得的 json 数据。
解决方案 2:
看看这个片段。
# reading the JSON data using json.load()
file = 'data.json'
with open(file) as train_file:
dict_train = json.load(train_file)
# converting json dataset from dictionary to dataframe
train = pd.DataFrame.from_dict(dict_train, orient='index')
train.reset_index(level=0, inplace=True)
希望有帮助:)
解决方案 3:
已接受答案的优化:
接受的答案存在一些功能问题,所以我想分享不依赖于 urllib2 的代码:
import requests
from pandas import json_normalize
url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'
response = requests.get(url)
dictr = response.json()
recs = dictr['result']['records']
df = json_normalize(recs)
print(df)
输出:
_id HourUTC HourDK ... ElbasAveragePriceEUR ElbasMaxPriceEUR ElbasMinPriceEUR
0 264028 2019-01-01T00:00:00+00:00 2019-01-01T01:00:00 ... NaN NaN NaN
1 138428 2017-09-03T15:00:00+00:00 2017-09-03T17:00:00 ... 33.28 33.4 32.0
2 138429 2017-09-03T16:00:00+00:00 2017-09-03T18:00:00 ... 35.20 35.7 34.9
3 138430 2017-09-03T17:00:00+00:00 2017-09-03T19:00:00 ... 37.50 37.8 37.3
4 138431 2017-09-03T18:00:00+00:00 2017-09-03T20:00:00 ... 39.65 42.9 35.3
.. ... ... ... ... ... ... ...
995 139290 2017-10-09T13:00:00+00:00 2017-10-09T15:00:00 ... 38.40 38.4 38.4
996 139291 2017-10-09T14:00:00+00:00 2017-10-09T16:00:00 ... 41.90 44.3 33.9
997 139292 2017-10-09T15:00:00+00:00 2017-10-09T17:00:00 ... 46.26 49.5 41.4
998 139293 2017-10-09T16:00:00+00:00 2017-10-09T18:00:00 ... 56.22 58.5 49.1
999 139294 2017-10-09T17:00:00+00:00 2017-10-09T19:00:00 ... 56.71 65.4 42.2
PS:API 为丹麦电价
解决方案 4:
只是接受答案的新版本,因为python3.x
不支持urllib2
from requests import request
import json
from pandas.io.json import json_normalize
path1 = '42.974049,-81.205203|42.974298,-81.195755'
response=request(url='http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false', method='get')
elevations = response.json()
elevations
data = json.loads(elevations)
json_normalize(data['results'])
解决方案 5:
您可以先将 json 数据导入 Python 字典中:
data = json.loads(elevations)
然后动态修改数据:
for result in data['results']:
result[u'lat']=result[u'location'][u'lat']
result[u'lng']=result[u'location'][u'lng']
del result[u'location']
重建 json 字符串:
elevations = json.dumps(data)
最后 :
pd.read_json(elevations)
您也可以避免将数据转储回字符串,我假设 Panda 可以直接从字典中创建 DataFrame(我很久没有使用它了:p)
解决方案 6:
使用 Json 加载文件并使用 DataFrame.from_dict 函数将其转换为 pandas 数据框
import json
import pandas as pd
json_string = '{ "name":"John", "age":30, "car":"None" }'
a_json = json.loads(json_string)
print(a_json)
dataframe = pd.DataFrame.from_dict(a_json)
解决方案 7:
这是一个将 JSON 转换为 DataFrame 并转回的小型实用程序类:希望您发现它有用。
# -*- coding: utf-8 -*-
from pandas.io.json import json_normalize
class DFConverter:
#Converts the input JSON to a DataFrame
def convertToDF(self,dfJSON):
return(json_normalize(dfJSON))
#Converts the input DataFrame to JSON
def convertToJSON(self, df):
resultJSON = df.to_json(orient='records')
return(resultJSON)
解决方案 8:
问题是数据框中有几列包含字典,而字典中又包含较小的字典。有用的 Json 通常是嵌套的。我一直在编写一些小函数,将我想要的信息提取到新列中。这样,我就可以以我想要的格式使用它了。
for row in range(len(data)):
#First I load the dict (one at a time)
n = data.loc[row,'dict_column']
#Now I make a new column that pulls out the data that I want.
data.loc[row,'new_column'] = n.get('key')
解决方案 9:
billmanH 的解决方案对我有帮助,但直到我从以下版本切换后才起作用:
n = data.loc[row,'json_column']
到:
n = data.iloc[[row]]['json_column']
这是其余部分,转换为字典有助于处理 json 数据。
import json
for row in range(len(data)):
n = data.iloc[[row]]['json_column'].item()
jsonDict = json.loads(n)
if ('mykey' in jsonDict):
display(jsonDict['mykey'])
解决方案 10:
#Use the small trick to make the data json interpret-able
#Since your data is not directly interpreted by json.loads()
>>> import json
>>> f=open("sampledata.txt","r+")
>>> data = f.read()
>>> for x in data.split("
"):
... strlist = "["+x+"]"
... datalist=json.loads(strlist)
... for y in datalist:
... print(type(y))
... print(y)
...
...
<type 'dict'>
{u'0': [[10.8, 36.0], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'1': [[10.8, 36.1], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'2': [[10.8, 36.2], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'3': [[10.8, 36.300000000000004], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'4': [[10.8, 36.4], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'5': [[10.8, 36.5], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'6': [[10.8, 36.6], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'7': [[10.8, 36.7], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'8': [[10.8, 36.800000000000004], {u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'9': [[10.8, 36.9], {u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
解决方案 11:
一旦您通过接受的答案获得了扁平化效果DataFrame
,您就可以将列制作成MultiIndex
(“花式多行标题”),如下所示:
df.columns = pd.MultiIndex.from_tuples([tuple(c.split('.')) for c in df.columns])
解决方案 12:
我更喜欢一种更通用的方法,其中可能用户不喜欢给出键“结果”。您仍然可以使用递归方法查找具有嵌套数据的键来展平它,或者如果您有键但您的 JSON 嵌套非常多。它类似于:
from pandas import json_normalize
def findnestedlist(js):
for i in js.keys():
if isinstance(js[i],list):
return js[i]
for v in js.values():
if isinstance(v,dict):
return check_list(v)
def recursive_lookup(k, d):
if k in d:
return d[k]
for v in d.values():
if isinstance(v, dict):
return recursive_lookup(k, v)
return None
def flat_json(content,key):
nested_list = []
js = json.loads(content)
if key is None or key == '':
nested_list = findnestedlist(js)
else:
nested_list = recursive_lookup(key, js)
return json_normalize(nested_list,sep="_")
key = "results" # If you don't have it, give it None
csv_data = flat_json(your_json_string,root_key)
print(csv_data)
解决方案 13:
Rumble通过 JSONiq 原生支持 JSON,并在 Spark 上运行,内部管理 DataFrames,因此您无需这样做——即使数据不是完全结构化的:
let $coords := "42.974049,-81.205203%7C42.974298,-81.195755"
let $request := json-doc("http://maps.googleapis.com/maps/api/elevation/json?locations="||$coords||"&sensor=false")
for $obj in $request.results[]
return {
"latitude" : $obj.location.lat,
"longitude" : $obj.location.lng,
"elevation" : $obj.elevation
}
结果可以导出为 CSV,然后以 DataFrame 的形式在任何其他主机语言中重新打开。
解决方案 14:
参考MongoDB 文档,我得到了以下代码:
from pandas import DataFrame
df = DataFrame('Your json string')
扫码咨询,免费领取项目管理大礼包!