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
Practical Data Analysis Cookbook
Practical Data Analysis Cookbook

Practical Data Analysis Cookbook: Over 60 practical recipes on data exploration and analysis

eBook
Mex$631.99 Mex$902.99
Paperback
Mex$1128.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Practical Data Analysis Cookbook

Chapter 2. Exploring the Data

In this chapter, we will cover various techniques that will allow you to understand your data better and explore relationships between features. You will learn the following recipes:

  • Producing descriptive statistics
  • Exploring correlations between features
  • Visualizing interactions between features
  • Producing histograms
  • Creating multivariate charts
  • Sampling the data
  • Splitting the dataset into training, cross-validation, and testing

Introduction

In the following recipes, we will use Python and D3.js to build our understanding of the data. We will analyze the distributions of all the variables, investigate the correlations between features, and visualize the interactions between them. You will learn how to generate histograms and present three-dimensional data on a two-dimensional chart. Finally, you will learn how to produce stratified samples and split your dataset into testing and training subsets.

Producing descriptive statistics

To fully understand the distribution of any random variable, we need to know its mean and standard deviation, minimum and maximum values, median, mode, first and third quartiles, skewness, and kurtosis.

Sometimes, it is good to perform statistical testing to confirm (or disprove) whether our data follows a specific distribution. This, however, is beyond the scope of this book.

Getting ready

To execute this recipe, all you need is pandas. No other prerequisites are required.

How to do it…

Here is a piece of code that can quickly give you a basic understanding of your data. We assume that our data was read from a CSV file and stored in the csv_read variable (the data_describe.py file):

# calculate the descriptives: count, mean, std,
# min, 25%, 50%, 75%, max
# for a subset of columns
csv_desc = csv_read[
    [  
        'beds','baths','sq__ft','price','s_price',
        'n_price','s_sq__ft&apos...

Exploring correlations between features

A correlation coefficient between two variables measures the degree of relationship between them. If the coefficient is equal to 1, we then say that the variables are perfectly correlated, if it is -1, then we conclude that the second variable is perfectly inversely correlated with the first one. The coefficient of 0 means that no measurable relationship exists between the two variables.

Note

We need to stress one fundamental truth here: one cannot conclude that simply if two variables are correlated, there exists a causal relationship between them. For more information, refer to the following website: https://web.cn.edu/kwheeler/logic_causation.html.

Getting ready

To execute this recipe, you need pandas. No other prerequisites are required.

How to do it…

We will be checking only correlations between the number of bedrooms that the apartment has, number of baths, the floor area, and price. Once again, we assume that the data is already in the csv_read...

Visualizing the interactions between features

D3.js is a powerful framework created by Mike Bostock to visualize data. It allows you to interactively manipulate data using HTML, SVG, and CSS. In this recipe, we will explore whether a relationship exists between the price of a property and the floor area.

Getting ready

To execute this recipe, you will need pandas and SQLAlchemy to prepare the data. For the visualization, all you need is the D3.js code (available in the GitHub repository for the book in the /Data/Chapter02/d3 folder). Some familiarity with HTML and JavaScript is required.

How to do it…

The code for this recipe comes in two parts: the data preparation (Python) and data visualization (HTML and D3.js).

The data preparation part is simple, and by now, you should be able to do it yourself. You can also refer to the Storing and retrieving from a relational database recipe from Chapter 1, Preparing the Data. We extract the data from the PostgreSQL database using SQLAlchemy. The...

Producing histograms

Histograms can help you inspect the distribution of any variable quickly. Histograms bin the observations into groups and present the count of observations in each group on a bar chart. It is a powerful and easy way to examine issues with your data as well as inspect visually if the data follows some known distribution.

In this recipe, we will produce histograms of all the prices from our dataset.

Getting ready

To run this recipe, you will need pandas and SQLAlchemy to retrieve the data. Matplotlib and Seaborn handle the presentation layer. Matplotlib is a 2D library for scientific data presentation. Seaborn builds on Matplotlib and provides an easier way to produce statistical charts (such as histograms, among others).

How to do it…

We assume that the data can be accessed from the PostgreSQL database. Check the Storing and retrieving from a relational database recipe from Chapter 1, Preparing the Data. The following code will produce a histogram of the prices and...

Creating multivariate charts

What the previous recipe showed is that only a handful of houses with less than two bedrooms were sold in the Sacramento area. In the Visualizing the interactions between features recipe, we used D3.js to present the relationship between the price and floor area. In this recipe, we will add an another dimension to the two-dimensional chart, the number of bedrooms.

Getting ready

To execute this recipe, you will need the pandas, SQLAlchemy, and Bokeh modules installed. No other prerequisites are required.

How to do it…

Bokeh is a module that marries Seaborn and D3.js: it produces visually appealing data visualizations (just like Seaborn) and allows you to interact with the chart, using D3.js in the backend of the produced HTML file. Producing a similar chart in D3.js would require more coding. The source code for this recipe is contained in the data_multivariate_charts.py file:

# prepare the query to extract the data from the database
query = 'SELECT beds...

Introduction


In the following recipes, we will use Python and D3.js to build our understanding of the data. We will analyze the distributions of all the variables, investigate the correlations between features, and visualize the interactions between them. You will learn how to generate histograms and present three-dimensional data on a two-dimensional chart. Finally, you will learn how to produce stratified samples and split your dataset into testing and training subsets.

Producing descriptive statistics


To fully understand the distribution of any random variable, we need to know its mean and standard deviation, minimum and maximum values, median, mode, first and third quartiles, skewness, and kurtosis.

Sometimes, it is good to perform statistical testing to confirm (or disprove) whether our data follows a specific distribution. This, however, is beyond the scope of this book.

Getting ready

To execute this recipe, all you need is pandas. No other prerequisites are required.

How to do it…

Here is a piece of code that can quickly give you a basic understanding of your data. We assume that our data was read from a CSV file and stored in the csv_read variable (the data_describe.py file):

# calculate the descriptives: count, mean, std,
# min, 25%, 50%, 75%, max
# for a subset of columns
csv_desc = csv_read[
    [  
        'beds','baths','sq__ft','price','s_price',
        'n_price','s_sq__ft','n_sq__ft','b_price',
        'p_price','d_Condo','d_Multi-Family',
    ...
Left arrow icon Right arrow icon

Key benefits

  • • Clean dirty data, extract accurate information, and explore the relationships between variables
  • • Forecast the output of an electric plant and the water flow of American rivers using pandas, NumPy, Statsmodels, and scikit-learn
  • • Find and extract the most important features from your dataset using the most efficient Python libraries

Description

Data analysis is the process of systematically applying statistical and logical techniques to describe and illustrate, condense and recap, and evaluate data. Its importance has been most visible in the sector of information and communication technologies. It is an employee asset in almost all economy sectors. This book provides a rich set of independent recipes that dive into the world of data analytics and modeling using a variety of approaches, tools, and algorithms. You will learn the basics of data handling and modeling, and will build your skills gradually toward more advanced topics such as simulations, raw text processing, social interactions analysis, and more. First, you will learn some easy-to-follow practical techniques on how to read, write, clean, reformat, explore, and understand your data—arguably the most time-consuming (and the most important) tasks for any data scientist. In the second section, different independent recipes delve into intermediate topics such as classification, clustering, predicting, and more. With the help of these easy-to-follow recipes, you will also learn techniques that can easily be expanded to solve other real-life problems such as building recommendation engines or predictive models. In the third section, you will explore more advanced topics: from the field of graph theory through natural language processing, discrete choice modeling to simulations. You will also get to expand your knowledge on identifying fraud origin with the help of a graph, scrape Internet websites, and classify movies based on their reviews. By the end of this book, you will be able to efficiently use the vast array of tools that the Python environment has to offer.

Who is this book for?

If you are a beginner or intermediate-level professional who is looking to solve your day-to-day, analytical problems with Python, this book is for you. Even with no prior programming and data analytics experience, you will be able to finish each recipe and learn while doing so.

What you will learn

  • • Read, clean, transform, and store your data usng Pandas and OpenRefine
  • • Understand your data and explore the relationships between variables using Pandas and D3.js
  • • Explore a variety of techniques to classify and cluster outbound marketing campaign calls data of a bank using Pandas, mlpy, NumPy, and Statsmodels
  • • Reduce the dimensionality of your dataset and extract the most important features with pandas, NumPy, and mlpy
  • • Predict the output of a power plant with regression models and forecast water flow of American rivers with time series methods using pandas, NumPy, Statsmodels, and scikit-learn
  • • Explore social interactions and identify fraudulent activities with graph theory concepts using NetworkX and Gephi
  • • Scrape Internet web pages using urlib and BeautifulSoup and get to know natural language processing techniques to classify movies ratings using NLTK
  • • Study simulation techniques in an example of a gas station with agent-based modeling

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 29, 2016
Length: 384 pages
Edition : 1st
Language : English
ISBN-13 : 9781783551668
Category :
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 29, 2016
Length: 384 pages
Edition : 1st
Language : English
ISBN-13 : 9781783551668
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 Mex$85 each
Feature tick icon Exclusive print discounts
$279.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 Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 2,974.97
Getting Started with Python Data Analysis
Mex$799.99
Practical Data Analysis Cookbook
Mex$1128.99
Practical Machine Learning
Mex$1045.99
Total Mex$ 2,974.97 Stars icon

Table of Contents

12 Chapters
1. Preparing the Data Chevron down icon Chevron up icon
2. Exploring the Data Chevron down icon Chevron up icon
3. Classification Techniques Chevron down icon Chevron up icon
4. Clustering Techniques Chevron down icon Chevron up icon
5. Reducing Dimensions Chevron down icon Chevron up icon
6. Regression Methods Chevron down icon Chevron up icon
7. Time Series Techniques Chevron down icon Chevron up icon
8. Graphs Chevron down icon Chevron up icon
9. Natural Language Processing Chevron down icon Chevron up icon
10. Discrete Choice Models Chevron down icon Chevron up icon
11. Simulations 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 Half star icon 4.8
(5 Ratings)
5 star 80%
4 star 20%
3 star 0%
2 star 0%
1 star 0%
Amazon Customer Nov 10, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book provides me with tools that I can use straight away on my research works. The feature I like the most is the coverage of 'lifespan' of data from preparation to analysis techniques that are commonly required by data analysts both in academia and industry. I have also used some examples from this book in teaching my senior classes in University. The coverage of analysis techniques is a great feature that completes a data analysis codebook. This book is great for learning and also a very good reference book for anyone who works with data and for researchers in the academia. Absolutely love it!
Amazon Verified review Amazon
nolan Jan 06, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The Practical Data Analysis Cookbook is a highly utility-oriented breakdown of data analysis expressed through python, which is very in-tune with the current state of the field.The author does a great job of illustrating current topics in data science, while maintaining emphasis on short and concise code. The entire thing is easy to read and process. Highly recommended if this is the area of study/interest in which you find yourself.
Amazon Verified review Amazon
Denny Lee Jan 07, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Practical Data Analysis Cookbook is the handy go-to reference for performing data analysis within the Python ecosystem. It starts you off by how to prepare and explore the data so you can actually start doing data analysis for your scenario. Then it dives into common Data Sciences techniques including (but not limited to) classification, clustering, dimensionality reduction, natural language processing and simulations. What's really helpful with this cookbook is that it contains practical data analysis techniques (as the title notes). For example, when working with k-means clustering, not only are you provided with how to do it and how it works, the recipe also notes the difference between working with scikit-learn vs. scipy. A great book whether you're an aspiring data scientist to being a great reference for a practicing data scientist.
Amazon Verified review Amazon
Joshua Allen May 15, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent reference full of recipes for common task patterns in the day-to-day life of a data scientist. The recipes are in detailed "hands on lab" style, and would be suitable for use in training events as well as reference.
Amazon Verified review Amazon
Jo Apr 29, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
While I work in the data science field, I was interested in doing some data analysis in Python and so turned to this book and found that this is a great introduction to practical data analysis and will help jumpstart anyone who is new to the field.It is easy to get overwhelmed by all the possible algorithms for any task and this focuses on just the important ones making it easy for someone to focus on. It is primarily for someone who likes to 'learn-by-doing' and not worry too much about the specific details of the algorithm.Some things that are awesome about this book -* Great introduction for someone looking to dive right into analysis* Skips the theory behind all the algorithms and jumps right into the practice* Focuses on just the important concepts required to dive right in rather than present all choices.* Very thorough and talks about all the important concepts that you need for* For someone new to Python (like me) gives a good place to start* Well structured - each section has a- 'Getting ready' bit talking about the pre-reqs- 'How to do it' which gives you the code snippets to apply the specific algorithm- 'How it works' talks about how exactly the code snippet works with some details on the algorithm- 'There's more' & 'see also' provides you with extra references and links.Some areas which may need you to refer else where -* If you're looking for deeper knowledge and the theory behind an algorithm* If you're looking for a detailed comparison on multiple algorithms, their trade-offs etc* If you're completely new to coding altogether you might need to supplement with additional materialIt's probably worth mentioning that I looked at a few other titles in this space and found that Data Analytics: Practical Data Analysis and Statistical Guide to Transform and Evolve Any Business Leveraging the Power of Data Analytics, Data Science, ... (Hacking Freedom and Data Driven Book 2) Seemed quite business focused and probably better suited for someone into BI Practical Data Analysis Multiple technologies covered and lots more choices, since I was just trying to focus on Python it didn't suit my needs as much.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.