2017-08-16 56 views
0

我试图从Api中提取数据,这应该给我某个区域的海洋条件。我有一些麻烦来拉取数据并将它们分离成单独的变量。理想情况下,我希望这些数据以数据框的形式出现,但我不介意以另一种方式出现。我没有这方面的经验,所以不知道我是否正确地做到了这一点。 我的代码:URL的Python Api将数据拉为数据框

dataLink = 
'http://magicseaweed.com/api/MYApiKEY/forecast/?spot_id=1407&units=eu' 
data = urllib.request.urlopen(dataLink) 
data = data.readline().decode("utf-8") 
data = json.loads(data) 
data = pd.DataFrame(data) 
swell = data[(data['charts']=='swell')] 

范例显示FORCAST:

[{"timestamp":1502755200,"localTimestamp":1502755200,"issueTimestamp":1502755200,"fadedRating":1,"solidRating":0,"swell":{"absMinBreakingHeight":0.61,"absMaxBreakingHeight":0.95,"unit":"m","minBreakingHeight":0.6,"maxBreakingHeight":0.9,"components":{"combined":{"height":1.2,"period":7,"direction":77.13,"compassDirection":"WSW"},"primary":{"height":1.2,"period":7,"direction":70.75,"compassDirection":"WSW"},"secondary":{"height":0.1,"period":11,"direction":92.74,"compassDirection":"W"}}},"wind":{"speed":18,"direction":90,"compassDirection":"W","chill":13,"gusts":25,"unit":"kph"},"condition":{"pressure":1013,"temperature":15,"weather":12,"unitPressure":"mb","unit":"c"},"charts":{"swell":"https:\/\/hist-1.msw.ms\/wave\/750\/1-1502755200-1.gif","period":"https:\/\/hist-1.msw.ms\/wave\/750\/1-1502755200-2.gif","wind":"https:\/\/hist-1.msw.ms\/gfs\/750\/1-1502755200-4.gif","pressure":"https:\/\/hist-1.msw.ms\/gfs\/750\/1-1502755200-3.gif","sst":"https:\/\/hist-1.msw.ms\/sst\/750\/1-1502755200-10.gif"}}, 
+0

你的数据不是一个格式,其中加载到数据框架中将是有益的与...合作。 –

+0

对于如何处理数据,您有什么建议吗?我不完全确定我在这方面做了什么,谢谢 –

+0

嗯....你的所有数据都遵循这种格式吗?那么,这可能是值得的。取决于你想要诚实地做什么。 –

回答

2

看来你需要json_normalize

from pandas.io.json import json_normalize 

data = json.loads(data) 
df = json_normalize(data) 
print (df) 

          charts.wind condition.pressure \ 
0 https:\/\/hist-1.msw.ms\/gfs\/750\/1-150275520...    1013 

    condition.temperature condition.unit condition.unitPressure \ 
0      15    c      mb 

    condition.weather ...  swell.maxBreakingHeight \ 
0     12 ...       0.9 

    swell.minBreakingHeight swell.unit timestamp wind.chill \ 
0      0.6   m 1502755200   13 

    wind.compassDirection wind.direction wind.gusts wind.speed wind.unit 
0      W    90   25   18  kph 

[1 rows x 38 columns]