Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Python Data Science Essentials
Python Data Science Essentials

Python Data Science Essentials: Become an efficient data science practitioner by thoroughly understanding the key concepts of Python

Arrow left icon
Profile Icon Alberto Boschetti
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (6 Ratings)
Paperback Apr 2015 258 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Alberto Boschetti
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (6 Ratings)
Paperback Apr 2015 258 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

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

Python Data Science Essentials

Chapter 2. Data Munging

We are just getting into action! In this new chapter, you'll essentially learn how to munge data. What does munging data imply?

The term munge is a technical term coined about half a century ago by the students of the Massachusetts Institute of Technology (MIT). Munging means to change, in a series of well-specified and reversible steps, a piece of original data to a completely different (and hopefully a more useful) one. Deep-rooted in hacker culture, munging is often heard in data science processes in parallel with other almost completely synonymous terms, such as data wrangling and data preparation.

Given such premises, in this chapter, the following topics will be covered:

  • The data science process (so you'll know what is going on and what's next)
  • Uploading data from a file
  • Selecting the data you need
  • Cleaning up missing or wrong data
  • Adding, inserting, and deleting data
  • Grouping and transforming data to obtain new, meaningful information
  • Managing...

The data science process

Although every data science project is different, for our illustrative purposes, we can partition them into a series of reduced and simplified phases.

The process starts with the obtaining of data, and this implies a series of possibilities, from simply uploading the data to assembling it from RDBMS or NoSQL repositories, and to synthetically generating it or scraping it from the web APIs or HTML pages.

Though this is a critical part of the data scientist's work, especially when faced with novel challenges, we will just briefly touch upon this aspect by offering the basic tools to get your data (even if it is too big) into your computer memory by using either a textual file present on your hard disk or the Web or using tables in RDBMS.

Then comes the data munging phase. Data will be inevitably always received in a form unsuitable for your analysis and experimentation. Thanks to a bunch of basic Python data structures and commands, you'll have to address...

Data loading and preprocessing with pandas

In the previous chapter, we discussed where to find useful datasets and examined basic import commands of Python packages. In this section, having kept your toolbox ready, you are about to learn how to structurally load, manipulate, preprocess, and polish data with pandas and NumPy.

Fast and easy data loading

Let's start with a CSV file and pandas. The pandas library offers the most accessible and complete function to load tabular data from a file (or a URL). By default, it will store the data into a specialized pandas data structure, index each row, separate variables by custom delimiters, infer the right data type for each column, convert data (if necessary), as well as parse dates, missing values, and erroneous values.

In: import pandas as pd
iris_filename = 'datasets-uci-iris.csv'
iris = pd.read_csv(iris_filename, sep=',', decimal='.', header=None, names= ['sepal_length', 'sepal_width', &apos...

Working with categorical and textual data

Typically, you'll find yourself dealing with two main kinds of data: categorical and numerical. Numerical data, such as temperature, amount of money, days of usage, or house number, can be composed of either floating point numbers (like 1.0, -2.3, 99.99, …) or integers (like -3, 9, 0, 1, …). Each value that the data can assume has a direct relation with others since they're comparable. In other words, you can say that a feature with a value of 2.0 is greater (actually, it is double) than a feature that assumes a value of 1.0. This type of data is very well-defined and comprehensible, with binary operators such as equal, greater, and less.

The other type of data you might see in your career is the categorical type. A categorical datum expresses an attribute that cannot be measured and assumes values in a finite or infinite set of values, often named levels. For example, weather is a categorical feature since it takes values...

Data processing with NumPy

Having introduced the essential pandas commands to upload and preprocess your data in memory completely, or even in smaller batches (or in single data rows), you'll have to work on it in order to prepare a suitable data matrix for your supervised and unsupervised learning procedures.

As a best practice, we suggest that you divide the task between a phase of your work when your data is still heterogeneous (a mix of numerical and symbolic values) and another phase when it is turned into a numeric table of data arranged in rows that represent your examples, and columns that contain the characteristic observed values of your examples, which are your variables.

In doing so, you'll have to wrangle between two key Python packages for scientific analysis, pandas and NumPy, and their two pivotal data structures, DataFrame and ndarray.

Since the target data structure is a NumPy ndarray object, let's start from the result we want to achieve.

NumPy's n-dimensional...

Creating NumPy arrays

There is more than one way to create NumPy arrays. The following are some of the ways:

  • Transforming an existing data structure into an array
  • Creating an array from scratch and populating it with default or calculated values
  • Uploading some data from a disk into an array

If you are going to transform an existing data structure, the odds are in favor of you working with a structured list or a pandas DataFrame.

From lists to unidimensional arrays

One of the most common situations you will encounter when working with data is the transforming of a list into an array.

When operating such a transformation, it is important to consider the objects the lists contain because this will determine the dimensionality and the dtype of the resulting array.

Let's start with the first example of a list containing just integers:

In: import numpy as np
In:  # Transform a list into a uni-dimensional array
list_of_ints = [1,2,3]
Array_1 = np.array(list_of_ints)
In: Array_1
Out: array([1, 2, 3...

The data science process


Although every data science project is different, for our illustrative purposes, we can partition them into a series of reduced and simplified phases.

The process starts with the obtaining of data, and this implies a series of possibilities, from simply uploading the data to assembling it from RDBMS or NoSQL repositories, and to synthetically generating it or scraping it from the web APIs or HTML pages.

Though this is a critical part of the data scientist's work, especially when faced with novel challenges, we will just briefly touch upon this aspect by offering the basic tools to get your data (even if it is too big) into your computer memory by using either a textual file present on your hard disk or the Web or using tables in RDBMS.

Then comes the data munging phase. Data will be inevitably always received in a form unsuitable for your analysis and experimentation. Thanks to a bunch of basic Python data structures and commands, you'll have to address all the problematic...

Data loading and preprocessing with pandas


In the previous chapter, we discussed where to find useful datasets and examined basic import commands of Python packages. In this section, having kept your toolbox ready, you are about to learn how to structurally load, manipulate, preprocess, and polish data with pandas and NumPy.

Fast and easy data loading

Let's start with a CSV file and pandas. The pandas library offers the most accessible and complete function to load tabular data from a file (or a URL). By default, it will store the data into a specialized pandas data structure, index each row, separate variables by custom delimiters, infer the right data type for each column, convert data (if necessary), as well as parse dates, missing values, and erroneous values.

In: import pandas as pd
iris_filename = 'datasets-uci-iris.csv'
iris = pd.read_csv(iris_filename, sep=',', decimal='.', header=None, names= ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'target'])

You can specify...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Quickly get familiar with data science using Python
  • Save tons of time through this reference book with all the essential tools illustrated and explained
  • Create effective data science projects and avoid common pitfalls with the help of examples and hints dictated by experience

Description

The book starts by introducing you to setting up your essential data science toolbox. Then it will guide you across all the data munging and preprocessing phases. This will be done in a manner that explains all the core data science activities related to loading data, transforming and fixing it for analysis, as well as exploring and processing it. Finally, it will complete the overview by presenting you with the main machine learning algorithms, the graph analysis technicalities, and all the visualization instruments that can make your life easier in presenting your results. In this walkthrough, structured as a data science project, you will always be accompanied by clear code and simplified examples to help you understand the underlying mechanics and real-world datasets.

Who is this book for?

If you are an aspiring data scientist and you have at least a working knowledge of data analysis and Python, this book will get you started in data science. Data analysts with experience of R or MATLAB will also find the book to be a comprehensive reference to enhance their data manipulation and machine learning skills.

What you will learn

  • Set up your data science toolbox using a Python scientific environment on Windows, Mac, and Linux
  • Get data ready for your data science project
  • Manipulate, fix, and explore data in order to solve data science problems
  • Set up an experimental pipeline to test your data science hypothesis
  • Choose the most effective and scalable learning algorithm for your data science tasks
  • Optimize your machine learning models to get the best performance
  • Explore and cluster graphs, taking advantage of interconnections and links in your data

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 30, 2015
Length: 258 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280429
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 30, 2015
Length: 258 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280429
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 98.98
Python Data Analysis
$54.99
Python Data Science Essentials
$43.99
Total $ 98.98 Stars icon
Banner background image

Table of Contents

7 Chapters
1. First Steps Chevron down icon Chevron up icon
2. Data Munging Chevron down icon Chevron up icon
3. The Data Science Pipeline Chevron down icon Chevron up icon
4. Machine Learning Chevron down icon Chevron up icon
5. Social Network Analysis Chevron down icon Chevron up icon
6. Visualization Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(6 Ratings)
5 star 66.7%
4 star 16.7%
3 star 0%
2 star 0%
1 star 16.7%
Filter icon Filter
Top Reviews

Filter reviews by




Sh Oct 06, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have some R experience and wanted to learn Python for data science. This book is great for that. Chapters are nicely layer out, starting from preprocessing, feature selection and then machine learning models. It even has a section on Restricted Boltzmann Machines for image analysis.
Amazon Verified review Amazon
Jay. L Dec 30, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
compared with other data science book in python, this one is thinner but still comprehensive. Not the best if you want to start learning all the tools and methods, but great for reviewing and refreshing what you've learnt from other places
Amazon Verified review Amazon
Bibliophage Jun 06, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am a senior engineer with years of experience working primarily in C, C#, perl, and T-SQL. I have basic python, and dusty memories of two years of college math. In the last year, my data set has ballooned at the rate of 1Tb every two months and will soon exceed the handling capacity of my old analytics stack. Blessed by my manager with a shiny new hadoop cluster and time to study, I'm learning new tricks. This book is one of the first I found, and for me it was perfect. It reads like a walk-through from a smart coworker: enough to get me going, the most important moving parts, a few gotchas, where to go for help, some simple working examples... It got me moving on my first project in just a few hours. This is the book I'd have written for myself.
Amazon Verified review Amazon
Oleg Okun Dec 06, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Although I am an experienced Data Scientist who knows well Python's stack for Data Science (scikit-learn, pandas, statsmodels, numpy, scipy, matplotlib, IPython), this book captured my attention and I have read a half of it during the first two days after getting the book. This book is easy to read for novices and experts alike (it does not contain a lot of math and wherever there are formulas they are not difficult to grasp), though some familiarity with Python packages comprising the Data Science stack will greatly facilitate material understanding. The writing style authors chose is excellent as it teaches readers in a very logical and pedagogically appealing way: the way of data pre-processing and analysis occur in projects that data scientists and engineers often encounter when aiming to solve the real-worlds tasks.The books begins with a description of how to install Python and various packages needed to run the code. The purpose of these packages is also explained. Different Python distributions are briefly discussed together with their characteristics, so that a reader can select a distribution particularly suitable to his/her needs. As all code examples in the book are run in IPython Notebook, special attention is paid to a short but comprehensive introduction into IPython itself. Data sets used in the book are described too.After advising on installation of Python and its packages, the book guides readers towards fast and easy data loading from a file, including the case when the entire data set cannot be loaded during one read in the memory and the solution offered is to load it in chunks by using pandas.Furthermore, answers to the following problems are provided: how to deal with erroneous records, how to treat categorical and text data, what are useful data cleansing and transformation operations implemented in pandas, how to use the optimized data structures - numpy arrays - and what operations on them can be done.Once data is loaded and converted to a suitable representation, the book then spends a chapter on the general Data Science pipeline that can be implemented with scikit-learn. The pipeline includes dimensionality reduction via either feature extraction or feature selection, outlier detection, predictive modeling (classification and regression), optimization of model's hyper-parameters, and model's performance evaluation. This material creates the holistic view what typical data analysis is comprised of.The next chapter introduces several popular machine learning algorithms in detail. Among them are linear and logistic regression, Naive Bayes, support vector machines, bagging and boosting ensembles. Special attention is paid to scikit-learn solutions of the 3Vs of big data: namely, volume, velocity and variety. Scalability with volume is solved with incremental learning when at any given moment of time, only a portion (batch) of the entire data fit to the available memory is used to update a model, hence, a model learns incrementally as new batches arrive. To keep up with velocity, scikit-learn offers a number of classification and regression algorithms optimized for speed. Data variety is deal with the help of hashing and sparse matrices. The chapter ends with short examples of doing basic operations of Natural Language Processing with the NLTK package and data clustering.Final two chapters are devoted to social network analysis with the NetworkX package and data visualization with the matplotlib and pandas packages, respectively.Although I have both paper and electronic versions of this book, I would advise first to buy the paper version as numerous code is much easier to understand in this format because one can see the entire snapshot at once.
Amazon Verified review Amazon
Mary Anne Thygesen Dec 18, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The book covers fundamentals of Data Science. Code for the book is available from the publisher. I used Anaconda Launcher which nicely converted the notebooks to jupyter and ran them well. My favorite chapter was chapter five Social Network Analysis. I like the table on graph examples, type, node and edges. It is useful for writing code.
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.