我想要做的是沿着纬度和经度坐标指定的路径从谷歌地图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()
Run Code Online (Sandbox Code Playgroud)
这给了我一个如下所示的数据:
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',
' }',
' ],',
' …Run Code Online (Sandbox Code Playgroud) 我正在使用CSV文件,其中几个列有一个简单的json对象(几个键值对),而其他列是正常的.这是一个例子:
name,dob,stats
john smith,1/1/1980,"{""eye_color"": ""brown"", ""height"": 160, ""weight"": 76}"
dave jones,2/2/1981,"{""eye_color"": ""blue"", ""height"": 170, ""weight"": 85}"
bob roberts,3/3/1982,"{""eye_color"": ""green"", ""height"": 180, ""weight"": 94}"
Run Code Online (Sandbox Code Playgroud)
使用后df = pandas.read_csv('file.csv'),解析stats列并将其拆分为其他列的最有效方法是什么?
大约一个小时后,我唯一能想到的是:
import json
stdf = df['stats'].apply(json.loads)
stlst = list(stdf)
stjson = json.dumps(stlst)
df.join(pandas.read_json(stjson))
Run Code Online (Sandbox Code Playgroud)
这似乎我做错了,考虑到我需要定期在三个列上执行此操作,这是相当多的工作.
*编辑:所需的输出是下面的数据框对象.添加以下代码行以我的(糟糕的)方式:
df = df.join(pandas.read_json(stjson))
del(df['stats'])
In [14]: df
Out[14]:
name dob eye_color height weight
0 john smith 1/1/1980 brown 160 76
1 dave jones 2/2/1981 blue 170 85
2 bob roberts 3/3/1982 green 180 94
Run Code Online (Sandbox Code Playgroud)