Hobart temperature

7/24/2017 hobart-temp.ipynb

Set up


In [1]:
import os
from urllib.request import urlretrieve
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('seaborn')

In [2]:
#https://stackoverflow.com/questions/11936967/text-file-parsing-with-python
def clean_data(filename):    

    inputfile = open(filename + '.txt')
    outputfile = open(filename + '.csv', 'w')
    
    outputfile.writelines('Date,Temp\n')
    for line in inputfile.readlines()[1:]:
        outputfile.writelines(','.join(line.split()).replace('99999.9', '') + '\n')        

    inputfile.close()
    outputfile.close()

In [3]:
def get_data(url, filename, force=False):
    if force or not os.path.exists(filename + '.txt'): 
        urlretrieve(url, filename + '.txt')
    if force or not os.path.exists(filename + '.csv'):
        clean_data(filename)

Get data


In [4]:
#http://www.bom.gov.au/climate/change/acorn-sat/#tabs=Data-and-networks

minURL = 'http://www.bom.gov.au/climate/change/acorn/sat/data/acorn.sat.minT.094029.daily.txt'
minFile = 'hobart-min'
get_data(minURL, minFile)

maxURL = 'http://www.bom.gov.au/climate/change/acorn/sat/data/acorn.sat.maxT.094029.daily.txt'
maxFile = 'hobart-max'
get_data(maxURL, maxFile)

In [5]:
minData = pd.read_csv('hobart-min.csv', index_col='Date', parse_dates=True)
maxData = pd.read_csv('hobart-max.csv', index_col='Date', parse_dates=True)
#data = pd.DataFrame.join(maxData, minData, how='outer', lsuffix='_Max', rsuffix="_Min" )
data = minData.merge(maxData, suffixes=('_Min', '_Max'), left_index=True, right_index=True)
data['Temp_Diff'] = data['Temp_Max'] - data['Temp_Min']

In [6]:
data.shape


Out[6]:
(36219, 3)

In [7]:
data.head()


Out[7]:
Temp_Min Temp_Max Temp_Diff
Date
1918-01-01 10.3 20.2 9.9
1918-01-02 13.2 20.0 6.8
1918-01-03 13.2 28.2 15.0
1918-01-04 19.6 19.8 0.2
1918-01-05 9.3 20.2 10.9

In [8]:
data.tail()


Out[8]:
Temp_Min Temp_Max Temp_Diff
Date
2017-02-24 13.4 21.2 7.8
2017-02-25 8.5 18.0 9.5
2017-02-26 9.7 24.1 14.4
2017-02-27 12.0 26.6 14.6
2017-02-28 14.2 26.6 12.4

In [9]:
data.describe()


Out[9]:
Temp_Min Temp_Max Temp_Diff
count 36123.000000 36180.000000 36085.000000
mean 8.724057 17.491993 8.766252
std 3.806929 4.950748 3.417750
min -2.800000 4.700000 -1.300000
25% 6.000000 13.800000 6.400000
50% 8.700000 17.100000 8.600000
75% 11.400000 20.400000 10.800000
max 25.800000 41.800000 26.200000

Exploratory visualisation


In [10]:
def apply_common(title=''):
    ax.set_ylim(-5,45)
    ax.set_title(title)
    ax.set_xlabel('Date')
    ax.set_ylabel('°Centrigrade')
    ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

In [11]:
data.hist()


Out[11]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000001827D8409E8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018200A8A908>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000018200AE6860>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018200B5E978>]], dtype=object)

In [12]:
ax = data.plot()
apply_common('All data')



In [28]:
plt.scatter(data['Temp_Max'], data.index, marker='.')
plt.show()



In [27]:
plt.scatter(data['Temp_Min'], data.index, marker='.')
plt.show()



In [26]:
plt.scatter(data['Temp_Diff'], data.index, marker='.')
plt.show()



In [16]:
filtered_data = data.dropna()
boxplot_data = [filtered_data['Temp_Max'], filtered_data['Temp_Min'], filtered_data['Temp_Diff']]
plt.boxplot(boxplot_data)
plt.xticks([1, 2, 3], ['maximum', 'minimum', 'difference'])
plt.show()



In [17]:
ax = data.resample('m').mean().plot()
apply_common('Monthly mean')



In [18]:
ax = data.resample('d').mean().rolling(365).mean().plot()
apply_common('Rolling 365-day mean')



In [19]:
ax = data.loc['2007-3-1':, 'Temp_Max'].resample('m').mean().plot()
apply_common('Ten year monthly mean')



In [20]:
ax = data.loc['2016-3-1':, 'Temp_Max'].resample('m').mean().plot()
apply_common('One year monthly mean')



In [21]:
ax = data.loc['2007-2-28':, 'Temp_Max'].resample('w').mean().plot()
apply_common('One year weekly mean')



In [22]:
ax = data.loc['2016-3-1':,'Temp_Max'].plot()
apply_common('One year daily')



In [23]:
#https://www.kaggle.com/miguelferia/visualization-of-temperature-data
#http://benalexkeen.com/resampling-time-series-data-with-pandas/
ax = data.resample('AS').mean().plot()
apply_common('Annual summary mean')



In [34]:
data['day#'] = data.index.dayofyear
fig, (ax1, ax2, ax3) = plt.subplots(nrows = 3, ncols = 1)
for key, grp in data.groupby(pd.TimeGrouper(freq='AS'), group_keys=False):
    ax1.plot(grp['day#'], grp['Temp_Max'], alpha=0.35)
    ax2.plot(grp['day#'], grp['Temp_Min'], alpha=0.35)
    ax3.plot(grp['day#'], grp['Temp_Diff'], alpha=0.35)
plt.show()