In [1]:
# We will probably need these
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
Real data is often stored in CSV files (Comma Separated Values).
So far, we have loaded csv files with the np.loadtxt
command.
The loadtxt
function has some basic functionality and works just fine, but when we have more elaborate data sets we want more sophisticated functionality.
The most powerful and advanced package for data handling and analysis is called pandas
. We will use only a few functions of the pandas
package here. Full information on pandas
can be found on the pandas website.
The file annual_precip.csv
contains the average yearly rainfall and total land area for all the countries in the world (well, there are some missing values); the data is available on the website of the world bank. Open the data file to see what it looks like (Notepad, Textedit, even Word if you have to). Load the data with the read_csv
function of pandas
, making sure that the names of the countries can be used to select a row, and perform the following tasks:
.head()
function.
In [2]:
rain = pd.read_csv('annual_precip.csv', skiprows=2, index_col=0)
# Examine the read file
print('First five lines of rain dataset:')
print(rain.head(10))
Get data for specific countries:
In [3]:
print('\nAverage annual rainfall in Panama is',rain.loc['Panama','precip'],'mm/year')
In [4]:
print('\nLand area of the Netherlands is', rain.loc['Netherlands','area'], 'thousand km^2/year')
In [5]:
print('\nCountries where average rainfall is below 200 mm/year')
print(rain[ rain.precip < 200 ])
In [6]:
print('\nCountries where average rainfall is above 2500 mm/year')
print(rain[ rain.precip > 2500 ])
In [7]:
print('Countries with almost the same rainfall as Netherlands')
print(rain[ abs(rain.loc['Netherlands','precip'] - rain.precip) < 50 ])
In time series data, one of the columns represents dates, sometimes including times, together referred to as datetimes. pandas
can be used to read csv files where one of the columns includes datetime data. You need to tell pandas
which column contains datetime values and pandas
will try to convert that column to datetime objects. Datetime objects are very convenient as specifics of the datetime object may be assessed with the dot syntax: .year
returns the year, .month
returns the month, etc.
For example, consider the following data stored in the file timeseries1.dat
date, conc
2014-04-01, 0.19
2014-04-02, 0.23
2014-04-03, 0.32
2014-04-04, 0.29
The file may be read with read_csv
using the keyword parse_dates=[0]
so that column number 0 is converted to datetimes
In [8]:
data = pd.read_csv('timeseries1.dat', parse_dates=[0])
print(data)
The rows of the DataFrame data
are numbered, as we have not told pandas
what column to use as the index of the rows. The first column of the DataFrame data
has datetime values. We can access, for example, the year, month, or day with the dot syntax
In [9]:
print('datetime of row 0:', data.iloc[0,0])
print('year of row 0:', data.iloc[0,0].year)
print('month of row 0:', data.iloc[0,0].month)
print('day of row 0:', data.iloc[0,0].day)
Time series data may also contain the time in addition to the date. For example, the data of the file timeseries2.dat
, shown below, contains the day and time. You can access the hour
or minutes
, but also the time of a row of the DataFrame with the .time()
function.
date, conc
2014-04-01 12:00:00, 0.19
2014-04-01 13:00:00, 0.20
2014-04-01 14:00:00, 0.23
2014-04-01 15:00:00, 0.21
In [10]:
data = pd.read_csv('timeseries2.dat', parse_dates=[0])
print(data)
print('hour of row 0:', data.iloc[0,0].hour)
print('minute of row 0:', data.iloc[0,0].minute)
print('time of row 0:', data.iloc[0,0].time())
Here we do the same thing, but additionally tell read_csv to use column 0 as index_col
In [11]:
data = pd.read_csv('timeseries2.dat', parse_dates=[0], index_col=0)
print(data)
data.plot(kind='bar')
plt.show()
Rainfall data for the Netherlands may be obtained from the website of the Royal Dutch Meteorological Society KNMI . Daily rainfall for the weather station Rotterdam in 2012 is stored in the file rotterdam_rainfall_2012.txt
. First open the file in a text editor to see what the file looks like. At the top of the file, an explanation is given of the data in the file. Read this. Load the data file with the read_csv
function of pandas
. Use the keyword skiprows
to skip all rows except for the row with the names of the columns. Use the keyword parse_dates
to give either the name or number of the column that needs to be converted to a datetime. Don't forget the skipinitialspace
keyword, else the names of the columns may start with a bunch of spaces. Perform the following tasks:
plot
function of pandas
to create a line plot of the daily rainfall with the number of the day (so not the date) along the horizontal axis. matplotlib
functions to add labels to the axes and set the limits along the horizontal axis from 0 to 365.
In [12]:
rain = pd.read_csv('rotterdam_rainfall_2012.txt',skiprows=9,
parse_dates=['YYYYMMDD'],skipinitialspace=True, index_col='YYYYMMDD')
rain.head(10)
Out[12]:
These data need some manipulation. The rain values are given in 0.1 mm/d where -1 means 0.0005 mm/d.
To convert the RH to mm/d, remove the station number and change the name of the index
We can drop the column 'STN' and the result is a DataFrame
In [13]:
rain.drop('STN', axis=1)
Out[13]:
We could also just select column 'RH' and then we obtain a time series.
In [14]:
rain = rain['RH']
In [15]:
rain
Out[15]:
rain[rain < 0] = 0.5 rain
This implies automatic conversion from int to float dtype.
Then divide by 10 to obtain mm/d.
In [16]:
rain = rain/10.
rain
Out[16]:
In [20]:
rain.plot()
plt.xlabel('day')
plt.ylabel('daily rainfall (mm/day)')
plt.show()
print('Maximum daily rainfall',rain.max())
print('Date of maximum daily rainfall',rain.argmax())
In this exercise we are going to compute the total monthly rainfall for 2012 in the City of Rotterdam using the daily rainfall measurements we loaded in the previous Exercise; later on in this Notebook we learn convenient functions from pandas
to do this, but here we are going to do this with a loop. Create an array of 12 zeros to store the monthly totals and loop through all the days in 2012 to compute the total rainfall for each month. The month associated with each row of the DataFrame may be obtained with the .month
syntax, as shown above. Print the monthly totals (in mm/month) to the screen and create a bar graph of the total monthly rainfall (in mm/month) vs. the month using the plt.bar
function of matplotlib.
In [22]:
rain.resample('M').sum()
Out[22]:
In [35]:
monthlyRain = rain.resample('M').sum()
monthlyRain.plot(kind='bar')
plt.xticks(np.arange(12),['J','F','M','A','M','J','J','A','S','O','N','D'])
plt.xlabel('month, 2012')
plt.ylabel('monthly rainfall (mm/month)')
plt.show()
In [102]:
data = read_csv('timeseries1.dat', parse_dates=[0], index_col=0)
print(data)
print('data on April 1:',data.loc['2014-04-01'])
print('data on April 2:',data.loc['2014-04-02'])
DataFrames have a very powerful feature called resampling. Downsampling refers to going from high frequency to low frequency. For example, going from daily data to monthly data. Upsampling refers to going from low frequency to high frequency. For example going from monthly data to daily data. For both upsampling and downsampling, you need to tell pandas
how to perform the resampling. Here we discuss downsampling, where we computed monthly totals from daily values. First we load the daily rainfall in Rotterdam in 2012 from the file rotterdam_rainfall_2012.txt
and specify the dates as the index (this is the column labeled as YYYYMMDD
). We resample the rain to monthly totals using the resample
function. You have to tell the resample
function to what frequency it needs to resample. Common ones are 'A'
for yearly, 'M'
for monthly, 'W'
for weekly, 'D'
for daily, and 'H'
for hourly, but there are many other ones (see here. The keyword argument how
is used to tell pandas
how to compute the resampled data. This can be many things, like 'mean'
for the mean (that is the default), 'sum'
for the total, 'min'
, 'max'
, etc. The keyword argument kind
is used to tell pandas
where to assign the computed value to. You can assign the computed value to the last day of the period, or the first day, or to the entire period (in this case the entire month). The latter is done by specifying kind='period'
, which is what we will do here. Calculating the montly totals and making a bar graph can now be done with pandas
as follows.
In [38]:
rain = pd.read_csv('rotterdam_rainfall_2012.txt', skiprows=9,
parse_dates=['YYYYMMDD'], index_col='YYYYMMDD',
skipinitialspace=True)
rain.RH[rain.RH<0] = 0.5
rain.RH = rain.RH * 0.1 # Convert to mm/day
monthlyrain = rain.RH.resample('M', kind='period').sum()
print(monthlyrain)
monthlyrain.plot(kind='bar')
plt.ylabel('mm/month')
plt.xlabel('month')
plt.show()
The file rotterdam_weather_2000_2010.txt
contains daily weather data at the weather station Rotterdam for the period 2000-2010 (again from the KNMI). Open the data file in an editor to see what is in it. Perform the following tasks:
plot
function of pandas
. Make sure to plot the mean temperature on the secondary $y$-axis (use the help function to find out how).
In [41]:
weather = pd.read_csv('rotterdam_weather_2000_2010.txt',skiprows=11,
parse_dates=['YYYYMMDD'],index_col='YYYYMMDD',skipinitialspace=True)
weather.TG = 0.1 * weather.TG
weather.RH = 0.1 * weather.RH
weather.EV24 = 0.1 * weather.EV24
weather.RH[weather.RH<0] = 0
yearly_rain = weather.RH.resample('A', kind='period').sum()
yearly_evap = weather.EV24.resample('A', kind='period').sum()
yearly_temp = weather.TG.resample('A', kind='period').mean()
yearly_rain.plot()
yearly_evap.plot()
yearly_temp.plot(secondary_y=True)
plt.xlabel('Year')
plt.ylabel('Rain/evap (mm/year)')
plt.show()
In [ ]: