I'm trying to fill a dataframe with historical hourly weather data. Done by calling the DarkSky API. However, sometimes certain fields will be missing and present a KeyError.
Here's what the API sends back for each hour:
'summary': 'Mostly cloudy throughout the day.',
'icon': 'partly-cloudy-day',
'data': [{
'time': 1528354800,
'summary': 'Partly Cloudy',
'icon': 'partly-cloudy-night',
'precipIntensity': 0,
'precipProbability': 0,
'temperature': 12.94,
'apparentTemperature': 12.94,
'dewPoint': 9.36,
'humidity': 0.79,
'pressure': 1011.4,
'windSpeed': 2.69,
'windGust': 2.69,
'windBearing': 252,
'cloudCover': 0.33,
'uvIndex': 0,
'visibility': 13.818}]
So when filling my dataframe I'll get a KeyError because sometimes precipIntensity
and precipProbability
won't be present and instead have one field called precipType
.
Here's how I'm trying to fill the dataframe:
VICTORIA = 48.407326, -123.329773
dt = datetime(2018, month, day).isoformat()
weather = forecast('APIKEY', *VICTORIA, time = dt)
weather.refresh(units='si')
for hour in weather['hourly']['data']:
daily_weather = daily_weather.append(
{'time': hour['time'],
'realtime': datetime.fromtimestamp(hour['time']),
'summary': hour['summary'],
'icon': hour['icon'],
'precipIntensity': hour['precipIntensity'],
'precipProbability': hour['precipProbability'],
'temperature': hour['temperature'],
'apparentTemperature': hour['apparentTemperature'],
'dewPoint': hour['dewPoint'],
'humidity': hour['humidity'],
'pressure': hour['pressure'],
'windSpeed': hour['windSpeed'],
'windBearing': hour['windBearing'],
'cloudCover': hour['cloudCover'],
'uvIndex': hour['uvIndex'],
'visibility': hour['visibility'],
}, ignore_index=True)
I've attempted to use try/except statements to make exceptions like so:
for hour in weather['hourly']['data']:
daily_weather = daily_weather.append(
{'time': hour['time'],
'realtime': datetime.fromtimestamp(hour['time']),
'summary': hour['summary'],
'icon': hour['icon'],
'temperature': hour['temperature'],
'apparentTemperature': hour['apparentTemperature'],
'dewPoint': hour['dewPoint'],
'humidity': hour['humidity'],
'pressure': hour['pressure'],
'windSpeed': hour['windSpeed'],
'windBearing': hour['windBearing'],
'cloudCover': hour['cloudCover'],
'uvIndex': hour['uvIndex'],
'visibility': hour['visibility'],
}, ignore_index=True)
try:
daily_weather = daily_weather.append({'precipIntensity': hour['precipIntensity'], 'precipProbability': hour['precipProbability']}, ignore_index=True)
except KeyError:
daily_weather = daily_weather.append({'precipType': hour['precipType']}, ignore_index=True)
However the precipIntensity
field fills in unused rows instead of being with the others:
I'd love some advice on how to use exception statements when trying to fill a dataframe. Thank you.