Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Clojure Data Analysis Cookbook - Second Edition
Clojure Data Analysis Cookbook - Second Edition

Clojure Data Analysis Cookbook - Second Edition: Dive into data analysis with Clojure through over 100 practical recipes for every stage of the analysis and collection process , Second Edition

eBook
€24.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Clojure Data Analysis Cookbook - Second Edition

Chapter 2. Cleaning and Validating Data

In this chapter, we will cover the following recipes:

  • Cleaning data with regular expressions
  • Maintaining consistency with synonym maps
  • Identifying and removing duplicate data
  • Regularizing numbers
  • Calculating relative values
  • Parsing dates and times
  • Lazily processing very large data sets
  • Sampling from very large data sets
  • Fixing spelling errors
  • Parsing custom data formats
  • Validating data with Valip

Introduction

You probably won't spend as much time to get the data as you will in trying to get it into shape. Raw data is often inconsistent, duplicated, or full of holes. Addresses might be missing, years and dates might be formatted in a thousand different ways, or names might be entered into the wrong fields. You'll have to fix these issues before the data is usable.

This is often an iterative, interactive process. If it's a very large dataset, I might create a sample to work with at this stage. Generally, I start by examining the data files. Once I find a problem, I try to code a solution, which I run on the dataset. After each change, I archive the data, either using a ZIP file or, if the data files are small enough, a version control system. Using a version control system is a good option because I can track the code to transform the data along with the data itself and I can also include comments about what I'm doing. Then, I take a look at the data again, and...

Cleaning data with regular expressions

Often, cleaning data involves text transformations. Some, such as adding or removing a set and static strings, are pretty simple. Others, such as parsing a complex data format such as JSON or XML, requires a complete parser. However, many fall within a middle range of complexity. These need more processing power than simple string manipulation, but full-fledged parsing is too much. For these tasks, regular expressions are often useful.

Probably, the most basic and pervasive tool to clean data of any kind is a regular expression. Although they're overused sometimes, regular expressions truly are the best tool for the job many times. Moreover, Clojure has a built-in syntax for compiled regular expressions, so they are convenient too.

In this example, we'll write a function that normalizes U.S. phone numbers.

Getting ready

For this recipe, we will only require a very basic project.clj file. It should have these lines:

(defproject cleaning-data &quot...

Maintaining consistency with synonym maps

One common problem with data is inconsistency. Sometimes, a value is capitalized, while sometimes it is not. Sometimes it is abbreviated, and sometimes it is full. At times, there is a misspelling.

When it's an open domain, such as words in a free-text field, the problem can be quite difficult. However, when the data represents a limited vocabulary (such as US state names, for our example here) there's a simple trick that can help. While it's common to use full state names, standard postal codes are also often used. A mapping from common forms or mistakes to a normalized form is an easy way to fix variants in a field.

Getting ready

For the project.clj file, we'll use a very simple configuration:

(defproject cleaning-data "0.1.0-SNAPSHOT"
  :dependencies [[org.clojure/clojure "1.6.0"]])

We just need to make sure that the clojure.string/upper-case function is available to us:

(use '[clojure.string :only (upper...

Identifying and removing duplicate data

One problem when cleaning up data is dealing with duplicates. How do we find them? What do we do with them once we have them? While a part of this process can be automated, often merging duplicated data is a manual task, because a person has to look at potential matches and determine whether they are duplicates or not and determining what needs to be done with the overlapping data. We can code heuristics, of course, but at some point, a person needs to make the final call.

The first question that needs to be answered is what constitutes identity for the data. If you have two items of data, which fields do you have to look at in order to determine whether they are duplicates? Then, you must determine how close they need to be.

For this recipe, we'll examine some data and decide on duplicates by doing a fuzzy comparison of the name fields. We'll simply return all of the pairs that appear to be duplicates.

Getting ready

First, we need to add the...

Regularizing numbers

If we need to read in numbers as strings, we have to worry about how they're formatted. However, we'll probably want the computer to deal with them as numbers, not as strings, and this can't happen if the string contains a comma or period to separate the thousands place. This allows the numbers to be sorted and to be available for mathematical functions.

In this recipe, we'll write a short function that takes a number string and returns the number. The function will strip out all of the extra punctuation inside the number and only leave the last separator. Hopefully, this will be the one that marks the decimal place.

Of course, the version of this function, which we'll see here, only works in locales that use commas to separate thousands and periods to separate decimals. However, it would be relatively easy to write versions that will work in any particular locale.

Getting ready

For this recipe, we're back to the most simple project.clj files...

Introduction


You probably won't spend as much time to get the data as you will in trying to get it into shape. Raw data is often inconsistent, duplicated, or full of holes. Addresses might be missing, years and dates might be formatted in a thousand different ways, or names might be entered into the wrong fields. You'll have to fix these issues before the data is usable.

This is often an iterative, interactive process. If it's a very large dataset, I might create a sample to work with at this stage. Generally, I start by examining the data files. Once I find a problem, I try to code a solution, which I run on the dataset. After each change, I archive the data, either using a ZIP file or, if the data files are small enough, a version control system. Using a version control system is a good option because I can track the code to transform the data along with the data itself and I can also include comments about what I'm doing. Then, I take a look at the data again, and the entire process starts...

Cleaning data with regular expressions


Often, cleaning data involves text transformations. Some, such as adding or removing a set and static strings, are pretty simple. Others, such as parsing a complex data format such as JSON or XML, requires a complete parser. However, many fall within a middle range of complexity. These need more processing power than simple string manipulation, but full-fledged parsing is too much. For these tasks, regular expressions are often useful.

Probably, the most basic and pervasive tool to clean data of any kind is a regular expression. Although they're overused sometimes, regular expressions truly are the best tool for the job many times. Moreover, Clojure has a built-in syntax for compiled regular expressions, so they are convenient too.

In this example, we'll write a function that normalizes U.S. phone numbers.

Getting ready

For this recipe, we will only require a very basic project.clj file. It should have these lines:

(defproject cleaning-data "0.1.0-SNAPSHOT...

Maintaining consistency with synonym maps


One common problem with data is inconsistency. Sometimes, a value is capitalized, while sometimes it is not. Sometimes it is abbreviated, and sometimes it is full. At times, there is a misspelling.

When it's an open domain, such as words in a free-text field, the problem can be quite difficult. However, when the data represents a limited vocabulary (such as US state names, for our example here) there's a simple trick that can help. While it's common to use full state names, standard postal codes are also often used. A mapping from common forms or mistakes to a normalized form is an easy way to fix variants in a field.

Getting ready

For the project.clj file, we'll use a very simple configuration:

(defproject cleaning-data "0.1.0-SNAPSHOT"
  :dependencies [[org.clojure/clojure "1.6.0"]])

We just need to make sure that the clojure.string/upper-case function is available to us:

(use '[clojure.string :only (upper-case)])

How to do it…

  1. For this recipe, we'll define...

Identifying and removing duplicate data


One problem when cleaning up data is dealing with duplicates. How do we find them? What do we do with them once we have them? While a part of this process can be automated, often merging duplicated data is a manual task, because a person has to look at potential matches and determine whether they are duplicates or not and determining what needs to be done with the overlapping data. We can code heuristics, of course, but at some point, a person needs to make the final call.

The first question that needs to be answered is what constitutes identity for the data. If you have two items of data, which fields do you have to look at in order to determine whether they are duplicates? Then, you must determine how close they need to be.

For this recipe, we'll examine some data and decide on duplicates by doing a fuzzy comparison of the name fields. We'll simply return all of the pairs that appear to be duplicates.

Getting ready

First, we need to add the library to...

Regularizing numbers


If we need to read in numbers as strings, we have to worry about how they're formatted. However, we'll probably want the computer to deal with them as numbers, not as strings, and this can't happen if the string contains a comma or period to separate the thousands place. This allows the numbers to be sorted and to be available for mathematical functions.

In this recipe, we'll write a short function that takes a number string and returns the number. The function will strip out all of the extra punctuation inside the number and only leave the last separator. Hopefully, this will be the one that marks the decimal place.

Of course, the version of this function, which we'll see here, only works in locales that use commas to separate thousands and periods to separate decimals. However, it would be relatively easy to write versions that will work in any particular locale.

Getting ready

For this recipe, we're back to the most simple project.clj files:

(defproject cleaning-data "0...

Calculating relative values


One way to normalize values is to scale frequencies by the sizes of their groups. For example, say the word truth appears three times in a document. This means one thing if the document has thirty words. It means something else if the document has 300 or 3,000 words. Moreover, if the dataset has documents of all these lengths, how do you compare the frequencies for words across documents?

One way to do this is to rescale the frequency counts. In some cases, we can just scale the terms by the length of the documents. Or, if we want better results, we might use something more complicated such as term frequency-inverse document frequency (TF-IDF).

For this recipe, we'll rescale some term frequencies by the total word count for their document.

Getting ready

We don't need much for this recipe. We'll use the minimal project.clj file, which is listed here:

(defproject cleaning-data "0.1.0-SNAPSHOT"
  :dependencies [[org.clojure/clojure "1.6.0"]])

However, it will be easier...

Parsing dates and times


One difficult issue when normalizing and cleaning up data is how to deal with time. People enter dates and times in a bewildering variety of formats; some of them are ambiguous, and some of them are vague. However, we have to do our best to interpret them and normalize them into a standard format.

In this recipe, we'll define a function that attempts to parse a date into a standard string format. We'll use the clj-time Clojure library, which is a wrapper around the Joda Java library (http://joda-time.sourceforge.net/).

Getting ready

First, we need to declare our dependencies in the Leiningen project.clj file:

(defproject cleaning-data "0.1.0-SNAPSHOT"
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [clj-time "0.9.0-beta1"]])

Then, we need to load these dependencies into our script or REPL. We'll exclude second from clj-time to keep it from clashing with clojure.core/second:

(use '[clj-time.core :exclude (extend second)]
     '[clj-time.format])

How to do...

Left arrow icon Right arrow icon

Description

This book is for those with a basic knowledge of Clojure, who are looking to push the language to excel with data analysis.

Who is this book for?

This book is for those with a basic knowledge of Clojure, who are looking to push the language to excel with data analysis.

What you will learn

  • Read data from a variety of data formats
  • Transform data to make it more useful and easier to analyze
  • Process data concurrently and in parallel for faster performance
  • Harness multiple computers to analyze big data
  • Use powerful data analysis libraries such as Incanter, Hadoop, and Weka to get things done quickly
  • Apply powerful clustering and data mining techniques to better understand your data

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 27, 2015
Length: 372 pages
Edition : 2nd
Language : English
ISBN-13 : 9781784399955
Category :
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 27, 2015
Length: 372 pages
Edition : 2nd
Language : English
ISBN-13 : 9781784399955
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 136.97
Mastering Clojure Data Analysis
€48.99
Clojure for Data Science
€41.99
Clojure Data Analysis Cookbook - Second Edition
€45.99
Total 136.97 Stars icon

Table of Contents

13 Chapters
1. Importing Data for Analysis Chevron down icon Chevron up icon
2. Cleaning and Validating Data Chevron down icon Chevron up icon
3. Managing Complexity with Concurrent Programming Chevron down icon Chevron up icon
4. Improving Performance with Parallel Programming Chevron down icon Chevron up icon
5. Distributed Data Processing with Cascalog Chevron down icon Chevron up icon
6. Working with Incanter Datasets Chevron down icon Chevron up icon
7. Statistical Data Analysis with Incanter Chevron down icon Chevron up icon
8. Working with Mathematica and R Chevron down icon Chevron up icon
9. Clustering, Classifying, and Working with Weka Chevron down icon Chevron up icon
10. Working with Unstructured and Textual Data Chevron down icon Chevron up icon
11. Graphing in Incanter Chevron down icon Chevron up icon
12. Creating Charts for the Web Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(2 Ratings)
5 star 0%
4 star 100%
3 star 0%
2 star 0%
1 star 0%
Fabio Mancinelli Jun 03, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a very interesting book with plenty of practical recipes about Data Analysis.The author goes through the different phases of Data Analysis, starting from the low level details about how to read data from actual sources, continuing on how to clean it up to obtain meaningful results and presenting different algorithms for actually performing data analysis.The recipes go from querying, aggregating data and displaying, to statistical analysis and machine learning (clustering and classification).Recipes are presented in a very clear way, and they give the reader a clear context where to apply them, how they work, actual working code to experiment with and some additional reference for getting more in-depth information.I really appreciated the fact the author is well versed both in the theorical aspect and in Clojure programming. He presents very important details about advanced topics like parallelism, concurrency and laziness, and warn the reader about the pitfalls to be aware of. For example when talking about lazy-data-reading he clearly explains how to correcly handle underlying resources explicitly showing the source of potential issues.I read also the first edition and I've found that almost all the common recipes have been updated, and also a new chapter about unstructured and textual data has been added.Even though I am not a data analyst this book was very clear, and gave me a lot of insights about how to deal with data. I will for sure apply some of these recipes in my daily work to make more sense of what happens in what I manage.
Amazon Verified review Amazon
armel esnault Apr 10, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Clojure Data Analysis Cookbook, Second Edition by EricRochester. Format ebook PDFTwo years after the first version Eric Rochester has published anupdated version of his book "Clojure Data Analysis Cookbook".The book gives a nice overview of data analysis in the clojureprogramming language. It provides hundreds of useful tips on varioussoftware such as Incanter: the clojure statistics platform or Weka: ajava platform for machine learning.The examples provided are easy to test assuming you have a basicknowledge of clojure (especially regarding the repl interaction). Asmost examples are independent from each other it is easy to pickrecipes without having to follow the whole chapter from the beginning.The first two chapter deal with the importation and the validation ofdata using common format such as XML,JSON,CSV or RDF. It appears to bevery useful as it is a mandatory step (usually the first) of dataanalysis. While it is not very complicated to do everything byyourself those tips may save you some time.Clojure has a very good concurrency and parallel model by default,which are usually covered in every clojure introduction book but you will stillfind information in this book that you don't find inothers. I particularly like the Monte Carlo and simulated annealing methodsthat find optimal partition size for parallel processing.Chapter 8 is perhaps less interresting becausse it covers Clojureinteraction with Mathematica and the R language. and the only reason touse them is when a big library or framework is not available inclojure and you have some constraints (e.g. time or performance) that preventyou from implementing it in clojure.As the title implies the book will not make you autonomous on dataanalysis but it would be good to have some tips and examples on how todesign and build a full scale data analysis oriented application.A good book for discovering and playing with data in Clojure.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.