1
Applied Data Analysis (CS401)
Robert West
Lecture 2
Handling data
Announcements
2
3
1st hour
refresher on data operations
2nd hour
data wrangling
The big picture
4
Key concept: structured data
A data model is a collection of concepts for describing data.
A schema is a description of a particular collection of data, using a given data model.
A toy model and schema
6
Meteorological measurements
Examples of data models
7
The relational model
8
id | name |
1 | Bush |
2 | Trump |
3 | Obama |
president | successor |
1 | 3 |
3 | 2 |
What is a relation?
Relation: made up of 2 parts:
Schema: specifies name of relation, plus name and type of each column
Students(sid: string, name: string, login: string, age: integer, gpa: real)
Instance: the actual data at a given time
#rows = cardinality
#fields = degree / arity
9
Example: instance of students relation
10
Cardinality = 3, degree = 5 , all rows distinct
sid
name
login
age
gpa
536
6
6
Jones
jones
s
18
5.4
8
8
Smith
smith@e
cs
18
5.2
536
5
0
Smith
smith
@m
ath
19
5.8
536
@c
e
SQL ex.
relation-list: A list of relation names
target-list: A list of attributes of tables in relation-list
qualification: Comparisons combined using AND, OR and NOT.
DISTINCT: optional keyword indicating that the answer should not contain duplicates.
11
SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
SELECT DISTINCT names
FROM students
WHERE age >= 19
Joins and inference
Chaining relations together is the basic inference method in relational DBs. It produces new relations (effectively new facts) from the data:
12
SELECT S.name, M.mortality
FROM Students S, Mortality M
WHERE S.Race=M.Race
Name | Race |
Socrates | Man |
Thor | God |
Barney | Dinosaur |
Blarney stone | Stone |
Race | Mortality |
Man | Mortal |
God | Immortal |
Dinosaur | Mortal |
Stone | Non-living |
M
S
Name | Mortality |
Socrates | Mortal |
Thor | Immortal |
Barney | Mortal |
Blarney stone | Non-living |
13
Aggregations and GroupBy
14
Aggregations and GroupBy
15
sid | name | course | semester | grade | gpa |
111 | Jones | Stat 134 | F13 | A | 4.0 |
111 | Jones | CS 162 | F13 | B- | 2.7 |
222 | Smith | EE 141 | S14 | B+ | 3.3 |
222 | Smith | CS162 | F14 | C+ | 2.3 |
222 | Smith | CS189 | F14 | A- | 3.7 |
SELECT sid, name, AVG(gpa)
FROM Students
GROUP BY sid
sid | name | gpa |
111 | Jones | 3.35 |
222 | Smith | 3.1 |
SQL is a declarative language
16
SQL implementations
etc.
17
SQL and “SQL”
18
“SQL”: Pandas/Python
19
Pandas operations (cf. Friday lab)
map() functions
filter (apply predicate to rows)
sort/group by
aggregate: sum, count, average, max, min
Pivot or reshape
Relational:
union, intersection, difference, cartesian product (CROSS JOIN), select/filter, project, join: natural join (INNER JOIN), theta join, semi-join, etc.
20
Pandas vs. SQL
+ Pandas is lightweight and fast.
+ Natively Python, i.e., full SQL expressiveness plus the expressiveness of Python, especially for function evaluation.
+ Integration with plotting functions like Matplotlib.
- Tables must fit into memory.
- No post-load indexing functionality: indices are built when a table is created.
- No transactions, journaling, etc.
- Large, complex joins are slower.
21
“SQL”: Apache Pig
22
Pig example
Suppose you have user info in one file, website logs in another, and you need to find the top 5 pages most visited by users aged 18-25.
23
Load Users
Load Pages
Filter by age
Join on name
Group on url
Count clicks
Order by clicks
Take top 5
Example from http://wiki.apache.org/pig-data/attachments/PigTalksPapers/attachments/ApacheConEurope09.ppt
In MapReduce
24
In Pig
25
Users = load ‘users’ as (name, age);�Filtered = filter Users by � age >= 18 and age <= 25; �Pages = load ‘pages’ as (user, url);�Joined = join Filtered by name, Pages by user;�Grouped = group Joined by url;�Summed = foreach Grouped generate group,� count(Joined) as clicks;�Sorted = order Summed by clicks desc;�Top5 = limit Sorted 5;
�store Top5 into ‘top5sites’;
“SQL”: Unix command line
26
cat users.txt \
| awk ‘$2 >= 18 && $2 <= 25’ \
| join -1 1 -2 1 pages.txt - \
| cut -f 4 \
| sort \
| uniq -c \
| sort -k 1,1 -n -r \
| head -n 5
Other data models: document model
<contact>� <id>656</id>� <firstname>Chuck</firstname>� <lastname>Smith</lastname>� <phone>(123) 555-0178</phone>� <phone>(890) 555-0133</phone>� <address>� <street1>Rue de l’Ale 8</street1>� <city>Lausanne</city>� <zip>1007</zip>� <country>CH</country>� </address>�</contact>
id | first name | ... |
656 | Chuck | ... |
... | ... | ... |
id | phone |
656 | (123) 555-0178 |
656 | (890) 555-0133 |
... | ... |
Other data models: network model
Data Wrangling
29
Working with raw data sucks
Data comes in all shapes and sizes
– CSV files, PDFs, SQL dumps, .jpg, …
Different files have different formatting
– Spaces instead of NULLs, extra rows
“Dirty” data: Unwanted anomalies, duplicates
30
Raw data without thinking ==
Recipe for disaster
31
What is data wrangling?
32
33
Types of data problems
34
“Dirty Data” horror stories
35
Diagnosing data problems
Visualizations and basic stats can convey issues in “raw” data
Different representations highlight different types of issues:
– Outliers often stand out in a plot
– Missing data will cause gaps or zero values
Becomes increasingly difficult as data gets larger�(sampling to the rescue!)
36
Facebook graph
37
Matrix view (1)
automatic permutation of rows and columns to highlight patterns of connectivity
38
Matrix view (2)
rows and columns sorted in the order provided by the Facebook API
Can you guess what’s going on?
39
Viz at scale? Careful!
40
Dealing with missing data
Knowledge about domain and data collection should drive your choice!
41
U.S. census counts of people working as ‘‘Farm Laborers’’; values from 1890 are missing due to records being burned in a fire
“My name is Willy”
42
First name | Last name |
Willy | NULL |
... | ... |
Data preparation
43
What to do before analysis
Deal with uncertain data (can arise from measurement errors, wrong sampling strategies, etc.)
Parse/transform data (with the techniques we saw during the first hour) to obtain meaningful records
44
Desiderata
It’s always ideal if you can put your hands on the code/documentation about the dataset you are analyzing (provenance)
It’s always ideal if the provided data format is nicely parsable (otherwise you need regexes, or maybe even pay humans)
45
Highly non-parseable data
Entire NY Times archive (since 1851) digitized as of 2015
46
What’s next?
What we have seen today is definitely not an exhaustive list (when you get stuck, Google is your friend!)
E.g., when we move to machine learning, we will learn how to prepare features (i.e., attributes) with normalization, rescaling, etc.
47
Don’t be surprised when multiple iterations are required!
48
Credits
49