Real world datasets are messy. There is no way around it: datasets have "holes" (missing data), the amount of formats in which data can be stored is endless, and the best structure to share data is not always the optimum to analyze them, hence the need to munge them. As has been correctly pointed out in many outlets (e.g.), much of the time spent in what is called (Geo-)Data Science is related not only to sophisticated modeling and insight, but has to do with much more basic and less exotic tasks such as obtaining data, processing,and turning them into a shape and form that makes analysis possible.
For how labor intensive and relevant this aspect is, there is surprisingly very little published on patterns, techniques, and best practices for quick and efficient data cleaning, manipulation, and transformation. In this session, you will use a few real world datasets and learn how to process them into Python so they can be transformed and manipulated, if necessary, and analyzed. For this, we will introduce some of the bread and butter of data analysis and scientific computing in Python. These are fundamental tools that are constantly used in almost any task relating to data analysis.
The first part shows how to quickly get data in and out of Python, so you can work on it and export it when ready; then the main part of the session discusses several patterns to clean and structure data properly, including tidying, subsetting, and aggregating; and we finish with some basic visualization. An additional extension presents more advanced tricks to manipulate tabular data.
Before we get our hands data-dirty, let us import all the additional libraries we will need, so we can get that out of the way and focus on the task at hand:
# This ensures visualizations are plotted inside the notebook
%matplotlib inline
import os # This provides several system utilities
import pandas as pd # This is the workhorse of data munging in Python
import seaborn as sns # This allows us to easily and beautifully plot
Throughout this notebook (and later on as well), we will use the CDRC's Census Data Pack for the city of Liverpool (link) and explore some of the city's socio-demogaphic characteristics. This is a large package crafted by the CDRC that brings together several Census tables in a consistent way for the city of Liverpool. We will only be able to use just a few of them but, since they are consistently organized, the procedure used should teach you how to explore other variables on your own. In particular, in this session, we will be using a table that lists population by country of birth.
The pack is composed of two types of data: tabular and spatial. Tabular data are numerical tables that contain information relating to many socio-economic variables for different units (areas); spatial data contains the geometries of the areas in which Liverpool is divided into. Since there are many variables contained in several tables, that can be linked to more than one geography, the pack also includes two "compass files" that help you find what you are looking for: one table that lists and describes the different datasets available; and a much more detailed table that lists and describes each and every single variable available in the pack.
The remainder assumes you have downloaded and unpacked the data. Specify the path to the folder in the following cell, so you can correctly run the code without errors:
# Important! You need to specify the path to the data in *your* machine
# If you have placed the data folder in the same directory as this notebook,
# you would do:
# path = 'Liverpool/'
path = '../../../../data/Liverpool/'
It is not only that data are not ready to analyze when you get a hold on them. Sometimes, there is not such thing as the dataset to analyze. Instead, what you have is a collection of separated files, sometimes with different structures, that you need to bring together to begin with. This is one of the areas where a bit of scripting skills can help you a long way. While in a traditional point-and-click program like Microsoft Excel or SPSS, you would have to repeat the steps every time you wanted to incorporate a new dataset, with a bit of Python ninja tricks, you can write code that will do it for you as many times as you need.
We will begin jumping straight into the analysis of population in Liverpool, organized by country of birth, at the Local Super Output Area (LSOA) level. Because the Census Data Pack contains a lot of data and very many different tables, you will have to bear with us and trust that what we are extracting is exactly the data of interest. This will speed up the process to walk through the reading, processing and manipulating of a dataset. Once you are familiar with these skills, the final section goes into how to explore the entire pack with more detail.
To read a "comma separated values" (.csv
) file, we can run:
lsoa_orig = pd.read_csv(path+'tables/QS203EW_lsoa11.csv', index_col='GeographyCode')
lsoa_orig.head()
Let us stop for a minute to learn how we have read the file. Here are the main aspects to keep in mind:
read_csv
from the pandas
library, which we have imported with the alias pd
.# Yours might look different if `path` is pointing somewhere else
path + 'tables/QS203EW_lsoa11.csv'
index_col
is not strictly necessary but allows us to choose one of the columns as the index of the table. More on indices below.read_csv
because the file we want to read is in the csv
format. However, pandas
allows for many more formats to be read (and written, just replace read
by to
! For example, read_csv
reads in, to_csv
writes out). A full list of formats supported includes:# This bit of code includes some more advanced tricks, not required for this session :-)
[i for i in dir(pd) if 'read_' in i]
If you want to learn how to use any of them, remember how to use the help
or ?
systems for inline help.
codebook
, so we can manipulate it later.Before we continue with the data, let us have a look at the object codebook
. It is a different "animal" than we have seen so far:
type(lsoa_orig)
It is a "pandas data frame". Similar to R's "data.frame" class, it is one of the most essential data structures in Python for data analysis, and we will use it intensively. Data frames are sophisticated costructs that can perform several advanced tasks and have many properties. We will be discovering them as we progress on the course but, for now, let us keep in mind they are tables, indexed on rows and columns that can support mixed data types and can be flexibly manipulated.
Now we have read the file, we can inspect it. For example, to show the first lines of the table:
lsoa_orig.head()
Let us also quickly check the dimensions of the table:
lsoa_orig.shape
This implies 298 rows by 78 columns. That is a lot of columns, all named under obscure codes. For now, just trust that the columns we want are:
region_codes = ['QS203EW0002', 'QS203EW0032', 'QS203EW0045', \
'QS203EW0063', 'QS203EW0072']
To keep only those with us, we can slice the table using the loc
operator:
lsoa_orig_sub = lsoa_orig.loc[:, region_codes]
lsoa_orig_sub.head()
Note how we use the operator loc
(for locator) on the dataframe, followed by squared brackets and, inside it, two alternatives:
:
to keep all the elements (rows in this case).We can further inspect the dataset with an additional command called info
, that lists the names of the columns and how many non-null elements each contains:
lsoa_orig_sub.info()
[Renaming columns]
IMPORTANT: some of the elemnts in this part are more advanced hence optional. If you want to move quickly through the lab, simply run the code cells without paying much attention to what it does. Once you have become more familiar with the rest of the tutorial, return here and work through the logic.
The table we have compiled contains exactly what we wanted. However, the names of the columns are a bit unintuitive, to say the least. It would be much handier if we could rename the columns into something more human readable. The easiest way to do that in pandas
is by creating a dictionary that maps the original name into the desired one, and then applying it to the DataFrame
with the command rename
. Let us walk through the steps necessary, one by one:
region_variables
), and what we have learnt about querying tables, combined with a small for
loop.First we need to bring up the variable names into a separate table (see the final section for more detail):
variables = pd.read_csv(path+'variables_description.csv', index_col=0)
code2name = {}
lookup_table = variables.set_index('ColumnVariableCode') # Reindex to be able to query
for code in region_codes:
code2name[code] = lookup_table.loc[code, 'ColumnVariableDescription']
code2name
": Total"
. A simple loop can help us:for code in code2name:
code2name[code] = code2name[code].replace(': Total', '')
code2name
lsoa_orig_sub = lsoa_orig_sub.rename(columns=code2name)
lsoa_orig_sub.head()
[Optional exercise. Difficulty: 2/5]
Take the subset table just created (lsoa_orig_sub
) and write it into a csv
file.
Now we are ready to start playing and interrogating the dataset! What we have at our fingertips is a table that summarizes, for each of the 238 LSOAs in Liverpool, how many people live in each, by the region of the world where they were born. To make what follows easier on your typing, let us rename the table to something shorter:
db = lsoa_orig_sub
Now, let us learn a few cool tricks built into pandas
that work out-of-the box with a table like ours.
head
(tail
). For example, for the top/bottom five lines:db.head(5)
db.tail(5)
db.info()
db.describe()
Note how the output is also a DataFrame
object, so you can do with it the same things you would with the original table (e.g. writing it to a file).
In this case, the summary might be better presented if the table is "transposed":
db.describe().T
db.min()
db['Europe'].max()
Note here how we have restricted the calculation of the maximum value to one column only.
Similarly, we can restrict the calculations to a single row:
db.loc['E01006512', :].std()
# Longer, hardcoded
total = db['Europe'] + db['Africa'] + db['Middle East and Asia'] + \
db['The Americas and the Caribbean'] + db['Antarctica and Oceania']
total.head()
# One shot
total = db.sum(axis=1)
total.head()
Note how we are using the command sum
, just like we did with max
or min
before but, in this case, we are not applying it over columns (e.g. the max of each column), but over rows, so we get the total sum of populations by areas.
Once we have created the variable, we can make it part of the table:
db['Total'] = total
db.head()
[Optional exercise. Difficulty: 3/5]
Obtain the total population in Liverpool by each subgroup.
Tip: focus on the axis argument.
# New variable with all ones
db['ones'] = 1
db.head()
And we can modify specific values too:
db.loc['E01006512', 'ones'] = 3
db.head()
del db['ones']
db.head()
We have already seen how to subset parts of a DataFrame
if we know exactly which bits we want. For example, if we want to extract the total and European population of the first four areas in the table, we use loc
with lists:
eu_tot_first4 = db.loc[['E01006512', 'E01006513', 'E01006514', 'E01006515'], \
['Total', 'Europe']]
eu_tot_first4
However, sometimes, we do not know exactly which observations we want, but we do know what conditions they need to satisfy (e.g. areas with more than 2,000 inhabitants). For these cases, DataFrames
support selection based on conditions. Let us see a few examples. Suppose we want to select...
... areas with more than 2,500 people in Total:
m5k = db.loc[db['Total'] > 2500, :]
m5k
... areas where there are no more than 750 Europeans:
nm5ke = db.loc[db['Europe'] < 750, :]
nm5ke
... areas with exactly ten person from Antarctica and Oceania:
oneOA = db.loc[db['Antarctica and Oceania'] == 10, :]
oneOA
Pro-tip: these queries can grow in sophistication with almost no limits. For example, here is a case where we want to find out the areas where European population is less than half the population:
eu_lth = db.loc[(db['Europe'] * 100. / db['Total']) < 50, :]
eu_lth
Now all of these queries can be combined with each other, for further flexibility. For example, imagine we want areas with more than 25 people from the Americas and Caribbean, but less than 1,500 in total:
ac25_l500 = db.loc[(db['The Americas and the Caribbean'] > 25) & \
(db['Total'] < 1500), :]
ac25_l500
Among the many operations DataFrame
objects support, one of the most useful ones is to sort a table based on a given column. For example, imagine we want to sort the table by total population:
db_pop_sorted = db.sort('Total', ascending=False)
db_pop_sorted.head()
If you inspect the help of db.sort
, you will find that you can pass more than one column to sort the table by. This allows you to do so-called hiearchical sorting: sort first based on one column, if equal then based on another column, etc.
[Optional exercise. Difficulty: 4/5]
db_pct
. The next step to continue exploring a dataset is to get a feel for what it looks like, visually. We have already learnt how to unconver and inspect specific parts of the data, to check for particular cases we might be intersted in. Now we will see how to plot the data to get a sense of the overall distribution of values. For that, we will be using the Python library seaborn
.
One of the simplest graphical devices to display the distribution of values in a variable is a histogram. Values are assigned into groups of equal intervals, and the groups are plotted as bars rising as high as the number of values into the group.
A histogram is easily created with the following command. In this case, let us have a look at the shape of the overall population:
_ = sns.distplot(db['Total'], kde=False)
Note we are using sns
instead of pd
, as the function belongs to seaborn
instead of pandas
.
We can quickly see most of the areas contain somewhere between 1,200 and 1,700 people, approx. However, there are a few areas that have many more, even up to 3,500 people.
An additinal feature to visualize the density of values is called rug
, and adds a little tick for each value on the horizontal axis:
_ = sns.distplot(db['Total'], kde=False, rug=True)
Histograms are useful, but they are artificial in the sense that a continuous variable is made discrete by turning the values into discrete groups. An alternative is kernel density estimation (KDE), which produces an empirical density function:
_ = sns.kdeplot(db['Total'], shade=True)
Another very common way of visually displaying a variable is with a line or a bar chart. For example, if we want to generate a line plot of the (sorted) total population by area:
_ = db['Total'].order(ascending=False).plot()
For a bar plot all we need to do is to change an argument of the call:
_ = db['Total'].order(ascending=False).plot(kind='bar')
Note that the large number of areas makes the horizontal axis unreadable. We can try to turn the plot around by displaying the bars horizontally (see how it's just changing bar
for barh
). To make it readable, let us expand the plot's height:
_ = db['Total'].order().plot(kind='barh', figsize=(6, 20))
[Optional exercise. Difficulty: 3/5]
sns.distplot
and sns.kdeplot
to discover additional arguments. Check also the tutorial.Happy families are all alike; every unhappy family is unhappy in its own way.
Leo Tolstoy.
Once you can read your data in, explore specific cases, and have a first visual approach to the entire set, the next step can be preparing it for more sophisticated analysis. Maybe you are thinking of modeling it through regression, or on creating subgroups in the dataset with particular characteristics, or maybe you simply need to present summary measures that relate to a slightly different arrangement of the data than you have been presented with.
For all these cases, you first need what statistitian, and general R wizard, Hadley Wickham calls "tidy data". The general idea to "tidy" your data is to convert them from whatever structure they were handed in to you into one that allows easy and standardized manipulation, and that supports directly inputting the data into what he calls "tidy" analysis tools. But, at a more practical level, what is exactly "tidy data"? In Wickham's own words:
Tidy data is a standard way of mapping the meaning of a dataset to its structure. A dataset is messy or tidy depending on how rows, columns and tables are matched up with observations, variables and types.
He then goes on to list the three fundamental characteristics of "tidy data":
If you are further interested in the concept of "tidy data", I recommend you check out the original paper (open access) and the public repository associated with it.
Let us bring in the concept of "tidy data" to our own Liverpool dataset. First, remember its structure:
db.head()
Thinking through tidy lenses, this is not a tidy dataset. It is not so for each of the three conditions:
GeographyCode
; and subgroups of an area. To tidy up this aspect, we can create two different tables:db_totals = db[['Total']]
db_totals.head()
# Note we use `drop` to exclude "Total", but we could also use a list with the names
# of all the columns to keep
db_subgroups = db.drop('Total', axis=1)
db_subgroups.head()
At this point, the table db_totals
is tidy: every row is an observation, every table is a variable, and there is only one observational unit in the table.
The other table (db_subgroups
), however, is not entirely tidied up yet: there is only one observational unit in the table, true; but every row is not an observation, and there are variable values as the names of columns (in other words, every column is not a variable). To obtain a fully tidy version of the table, we need to re-arrange it in a way that every row is a population subgroup in an area, and there are three variables: GeographyCode
, population subgroup, and population count (or frequency).
Because this is actually a fairly common pattern, there is a direct way to solve it in pandas
:
tidy_subgroups = db_subgroups.stack()
tidy_subgroups.head()
The method stack
, well, "stacks" the different columns into rows. This fixes our "tidiness" problems but the type of object that is returning is not a DataFrame
:
type(tidy_subgroups)
It is a Series
, which really is like a DataFrame
, but with only one column. The additional information (GeographyCode
and population group) are stored in what is called an multi-index. We will skip these for now, so we would really just want to get a DataFrame
as we know it out of the Series
. This is also one line of code away:
tidy_subgroupsDF = tidy_subgroups.reset_index()
tidy_subgroupsDF.head()
And some basic renaming of the columns:
tidy_subgroupsDF = tidy_subgroupsDF.rename(columns={'level_1': 'Subgroup', 0: 'Freq'})
tidy_subgroupsDF.head()
Now our table is fully tidied up!
One of the advantage of tidy datasets is they allow to perform advanced transformations in a more direct way. One of the most common ones is what is called "group-by" operations. Originated in the world of databases, these operations allow you to group observations in a table by one of its labels, index, or category, and apply operations on the data group by group.
For example, given our tidy table with population subgroups, we might want to compute the total sum of population by each group. This task can be split into two different ones:
Freq
for each of them.To do this in pandas
, meet one of its workhorses, and also one of the reasons why the library has become so popular: the groupby
operator.
pop_grouped = tidy_subgroupsDF.groupby('Subgroup')
pop_grouped
The object pop_grouped
still hasn't computed anything, it is only a convenient way of specifying the grouping. But this allows us then to perform a multitude of operations on it. For our example, the sum is calculated as follows:
pop_grouped.sum()
Similarly, you can also obtain a summary of each group:
pop_grouped.describe()
Pro-tip: since we only have one variable (Freq
), a more compact way to display that summary can be obtaine with the counterpart of stack
, unstack
:
pop_grouped.describe().unstack()
We will not get into it today as it goes beyond the basics we want to conver, but keep in mind that groupby
allows you to not only call generic functions (like sum
or describe
), but also your own functions. This opens the door for virtually any kind of transformation and aggregation possible.
[Optional exercise. Difficulty: 4/5]
Practice your data tidying skills with a different dataset. For example, you can have a look at the Guardian's version of Wikileaks' Afghanistan war logs. The table is stored on a GoogleDoc on the following address:
https://docs.google.com/spreadsheets/d/1EAx8_ksSCmoWW_SlhFyq2QrRn0FNNhcg1TtDFJzZRgc/edit?hl=en#gid=1
And its structure is as follows:
from IPython.display import IFrame
url = 'https://docs.google.com/spreadsheets/d/1EAx8_ksSCmoWW_SlhFyq2QrRn0FNNhcg1TtDFJzZRgc/edit?hl=en#gid=1'
IFrame(url, 700, 400)
Follow these steps:
csv
file (File --> Download as --> .csv, current sheet).[Optional extension]
We started this notebook assuming we already knew what variables in particular we wanted, out of the hundreds available on the Liverpool Census Data Pack. Unfortunately, that is not always the case, and sometimes you have to explore an entire dataset by yourself to find what you are looking for. To dip your toes into the sea of the Census Data Pack, in this section we will walk through how to systematically identify a variable and extract it.
The folder contains data at different scales. We will be using the Local Super Output Area (LSOAs). The folder is structured in the following way:
os.listdir(path)
For now, we will ignore the spatial information contained in the folder shapefiles
and focus on the tables
one. If you have a peek at the folder, it contains many files. You can get their names into a Python list with the following command:
csvs = os.listdir(path + 'tables')
And count them using the core fuction len
, which returns the length of a list:
len(csvs)
That is right, 303 files! Luckily, to navigate that sea of seemingly non-sensical letters, there is a codebook that explains things a bit. You can open it with a text editor or a spreadsheet program but, since it is a csv
file, we can also ingest it with Python:
codebook = pd.read_csv(path + 'datasets_description.csv', index_col=0)
Now we have read the file, we can inspect it. For example, to show the first lines of the table:
codebook.head()
You can use the index chosen to query rows. For example, if we want to see what dataset code QS203EW
corresponds to:
codebook.loc['QS203EW', 'DatasetTitle']
If we want to see what that dataset contains, there is another file in the folder called variables_description.csv
that has further information. We can bring it in the same way we did before and, again, we will index it using the first column of the table, the ID of the dataset where the variable belongs to:
variables = pd.read_csv(path+'variables_description.csv', index_col=0)
To have a sense of how large it is, we can call its shape
property, which returns the number of rows and columns, respectively:
variables.shape
2,563 different variables!!! Let us see what the structure of the table is:
variables.head()
If we are interested in exploring the country of birth (code QS203EW
), we can subset the table using loc
in a similar way as before. The only difference is that now we do not want to restrict the column to only one, so we use the colon :
instead of a particular name, including thus all the columns. Let us also save the subset by assigning it to a new object, birth_orig
:
birth_orig = variables.loc['QS203EW', :]
birth_orig.shape
To be clear, the table above contains all the variables that the dataset QS203EW
is comprised of. This means that, for every row in this table, there is a column in the actual dataset which, for the LSOAs, is on the file QS203EW_lsoa11.csv
, in the tables
folder.
This is still a lot. Arguably, to get a first sense of the data and start exploring it, we do not need every single disaggregation available. Let us look at the names and codes of the first 25 variables to see if we can spot any pattern that helps us simplify (note how we now use :
first to indicate we want all the rows):
birth_orig.loc[:, ['ColumnVariableCode', 'ColumnVariableDescription']].head(25)
Note how we have been able to pass a list of variables we wanted to select as columns, and pandas
has returned the dataframe "sliced" with only those, cutting off the rest.
It looks like the variable name follows a hierarchical pattern that dissaggregates by regions of the world. A sensible first approach might be to start considering only the largest regions. To do that, we need a list of the variable name for those aggregates since, once we have it, subsetting the dataframe will be straightforward. There are several ways we can go about it:
region_codes = ['QS203EW0002', 'QS203EW0032', 'QS203EW0045', \
'QS203EW0063', 'QS203EW0072']
[Advanced extension. Optional]
for
loops and if
statements and combine them with new ones about working with strings.regions = []
for var in birth_orig['ColumnVariableDescription']:
# Split the name of the variable in pieces by ': '
pieces = var.split(': ')
# Keep the first one (top hierarchy) and append ': Total'
name = pieces[0] + ': Total'
# If the name create matches the variable (exists in the original list),
# add the name to the list
if name == var:
regions.append(name)
regions
Let us work slowly by each step of this loop:
ColumnVariableDescription
).": "
as the points in the string where we want to break it, obtaining a list with the resulting pieces. For instance if we have Europe: Total
, we essentially do:'Europe: Total'.split(': ')
": Total"
, obtaining the string we want to keep:'Europe' + ': Total'
Now we have the names, we need to convert them into the codes. There are several ways to go about it, but here we will show one that relies on the indexing capabilities of pandas
. Essentially we take birth_orig
and index it on the names of the variables, to then subset it, keeping only those in our list (the variables we want to retain).
subset = birth_orig.set_index('ColumnVariableDescription').reindex(regions)
subset
Once this is done, all left to do is to retrieve the codes:
region_codes = list(subset.ColumnVariableCode)
region_codes
Which is the same that we hardcoded originally, only it has been entirely picked up by the python program, not a human.
Geographic Data Science'15 - Lab 2 by Dani Arribas-Bel is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.