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

eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Netherlands

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Netherlands

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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
€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 74.98
Python Data Science Essentials
€32.99
Python Data Analysis
€41.99
Total 74.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela