Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Python Data Cleaning Cookbook
Python Data Cleaning Cookbook

Python Data Cleaning Cookbook: Prepare your data for analysis with pandas, NumPy, Matplotlib, scikit-learn, and OpenAI , Second Edition

eBook
$27.98 $39.99
Paperback
$39.98 $49.99
Subscription
Free Trial
Renews at $19.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
Table of content icon View table of contents Preview book icon Preview Book

Python Data Cleaning Cookbook

Anticipating Data Cleaning Issues When Working with HTML, JSON, and Spark Data

This chapter continues our work on importing data from a variety of sources and the initial checks we should do on the data after importing it. Over the last 25 years, data analysts have found that they increasingly need to work with data in non-tabular, semi-structured forms. Sometimes, they even create and persist data in those forms. We will work with a common alternative to traditional tabular datasets in this chapter, JSON, but the general concepts can be extended to XML and NoSQL data stores such as MongoDB. We will also go over common issues that occur when scraping data from websites.

Data analysts have also been finding that increases in the volume of data to be analyzed have been even greater than improvements in machine processing power, at least those computing resources that are available locally. Working with big data sometimes requires us to rely on technology like Apache Spark, which...

Technical requirements

You will need pandas, NumPy, and Matplotlib to complete the recipes in this chapter. I used pandas 2.1.4, but the code will run on pandas 1.5.3 or later.

The code in this chapter can be downloaded from the book’s GitHub repository, https://github.com/PacktPublishing/Python-Data-Cleaning-Cookbook-Second-Edition.

Importing simple JSON data

JavaScript Object Notation (JSON) has turned out to be an incredibly useful standard for transferring data from one machine, process, or node to another. Often, a client sends a data request to a server, upon which that server queries the data in local storage and then converts it from something like an SQL Server, MySQL, or PostgreSQL table or tables into JSON, which the client can consume. This is sometimes complicated further by the first server (say, a web server) forwarding the request to a database server. JSON facilitates this, as does XML, by doing the following:

  • Being readable by humans
  • Being consumable by most client devices
  • Not being limited in structure

JSON is quite flexible, which means that it can accommodate just about anything, no matter how unwise. The structure can even change within a JSON file, so different keys might be present at different points. For example, the file might begin with some explanatory...

Importing more complicated JSON data from an API

In the previous recipe, we discussed one significant advantage (and challenge) of working with JSON data – its flexibility. A JSON file can have just about any structure its authors can imagine. This often means that this data does not have the tabular structure of the data sources we have discussed so far and that pandas DataFrames have. Often, analysts and application developers use JSON precisely because it does not insist on a tabular structure. I know I do!

Retrieving data from multiple tables often requires us to do a one-to-many merge. Saving that data to one table or file means duplicating data on the “one” side of the one-to-many relationship. For example, student demographic data is merged with data on the courses studied, and the demographic data is repeated for each course. With JSON, duplication is not required to capture these items of data in one file. We can have data on the courses studied nested...

Importing data from web pages

We use Beautiful Soup in this recipe to scrape data from a web page and load that data into pandas. Web scraping is very useful when there is data on a website that is updated regularly but there is no API. We can rerun our code to generate new data whenever the page is updated.

Unfortunately, the web scrapers we build can be broken when the structure of the targeted page changes. That is less likely to happen with APIs because they are designed for data exchange and carefully curated with that end in mind. The priority for most web designers is the quality of the display of information, not the reliability and ease of data exchange. This causes data cleaning challenges that are unique to web scraping, including HTML elements that house the data in surprising and changing locations, formatting tags that obfuscate the underlying data, and explanatory text that aid data interpretation being difficult to retrieve. In addition to these challenges, scraping...

Working with Spark data

When working with large datasets, we sometimes need to rely on distributed resources to clean and manipulate our data. With Apache Spark, analysts can take advantage of the combined processing power of many machines. We will use PySpark, a Python API for working with Spark, in this recipe. We will also go over how to use PySpark tools to take a first look at our data, select parts of our data, and generate some simple summary statistics.

Getting ready

To run the code in this section, you need to get Spark running on your computer. If you have installed Anaconda, you can follow these steps to work with Spark:

  1. Install Java with conda install openjdk.
  2. Install PySpark with conda install pyspark or conda install -c conda forge pyspark.
  3. Install findspark with conda install -c conda-forge findspark.

    Note

    Installation of PySpark can be tricky, particularly setting the necessary environment variables. While findspark...

Persisting JSON data

There are several reasons why we might want to serialize a JSON file:

  • We may have retrieved the data with an API but need to keep a snapshot of the data.
  • The data in the JSON file is relatively static and informs our data cleaning and analysis over multiple phases of a project.
  • We might decide that the flexibility of a schema-less format such as JSON helps us solve many data cleaning and analysis problems.

It is worth highlighting this last reason to use JSON – that it can solve many data problems. Although tabular data structures clearly have many benefits, particularly for operational data, they are often not the best way to store data for analysis purposes. In preparing data for analysis, a substantial amount of time is spent either merging data from different tables or dealing with data redundancy when working with flat files. Not only are these processes time-consuming but every merge or reshaping leaves the door open...

Versioning data

There may be times when we want to persist data without overwriting a prior version of the data file. This can be accomplished by appending a time stamp to a filename or a unique identifier. However, there are more elegant solutions available. One such solution is the Delta Lake library, which we will explore in this recipe.

We will work with the land temperature data again in this recipe. We will load the data, save it to a data lake, and then save an altered version to the same data lake.

Getting ready

We will be using the Delta Lake library in this recipe, which can be installed with pip install deltalake. We will also need the os library so that we can make a directory for the data lake.

How to do it...

You can get started with the data and version it as follows:

  1. We start by importing the Delta Lake library. We also create a folder called temps_lake for our data versions:
    import pandas as pd
    from deltalake.writer import write_deltalake...

Summary

The recipes in this chapter examined importing and data preparation of non-tabular data in a variety of forms, including JSON and HTML. We introduced Spark for working with big data and discussed how to persist tabular and non-tabular data. We also examined how to create a data lake for versioning. We will learn how to take the measure of our data in the next chapter.

Join our community on Discord

Join our community’s Discord space for discussions with the author and other readers:

https://discord.gg/p8uSgEAETX

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Get to grips with new techniques for data preprocessing and cleaning for machine learning and NLP models
  • Use new and updated AI tools and techniques for data cleaning tasks
  • Clean, monitor, and validate large data volumes to diagnose problems using cutting-edge methodologies including Machine learning and AI

Description

Jumping into data analysis without proper data cleaning will certainly lead to incorrect results. The Python Data Cleaning Cookbook - Second Edition will show you tools and techniques for cleaning and handling data with Python for better outcomes. Fully updated to the latest version of Python and all relevant tools, this book will teach you how to manipulate and clean data to get it into a useful form. he current edition focuses on advanced techniques like machine learning and AI-specific approaches and tools for data cleaning along with the conventional ones. The book also delves into tips and techniques to process and clean data for ML, AI, and NLP models. You will learn how to filter and summarize data to gain insights and better understand what makes sense and what does not, along with discovering how to operate on data to address the issues you've identified. Next, you’ll cover recipes for using supervised learning and Naive Bayes analysis to identify unexpected values and classification errors and generate visualizations for exploratory data analysis (EDA) to identify unexpected values. Finally, you’ll build functions and classes that you can reuse without modification when you have new data. By the end of this Data Cleaning book, you'll know how to clean data and diagnose problems within it.

Who is this book for?

This book is for anyone looking for ways to handle messy, duplicate, and poor data using different Python tools and techniques. The book takes a recipe-based approach to help you to learn how to clean and manage data with practical examples. Working knowledge of Python programming is all you need to get the most out of the book.

What you will learn

  • Using OpenAI tools for various data cleaning tasks
  • Producing summaries of the attributes of datasets, columns, and rows
  • Anticipating data-cleaning issues when importing tabular data into pandas
  • Applying validation techniques for imported tabular data
  • Improving your productivity in pandas by using method chaining
  • Recognizing and resolving common issues like dates and IDs
  • Setting up indexes to streamline data issue identification
  • Using data cleaning to prepare your data for ML and AI models

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 31, 2024
Length: 486 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803246291
Category :
Languages :
Concepts :

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

Product Details

Publication date : May 31, 2024
Length: 486 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803246291
Category :
Languages :
Concepts :

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 $ 109.94 149.97 40.03 saved
Building LLM Powered  Applications
$34.98 $49.99
Python Data Cleaning Cookbook
$39.98 $49.99
The Machine Learning Solutions Architect Handbook
$34.98 $49.99
Total $ 109.94 149.97 40.03 saved Stars icon

Table of Contents

13 Chapters
Anticipating Data Cleaning Issues When Importing Tabular Data with pandas Chevron down icon Chevron up icon
Anticipating Data Cleaning Issues When Working with HTML, JSON, and Spark Data Chevron down icon Chevron up icon
Taking the Measure of Your Data Chevron down icon Chevron up icon
Identifying Outliers in Subsets of Data Chevron down icon Chevron up icon
Using Visualizations for the Identification of Unexpected Values Chevron down icon Chevron up icon
Cleaning and Exploring Data with Series Operations Chevron down icon Chevron up icon
Identifying and Fixing Missing Values Chevron down icon Chevron up icon
Encoding, Transforming, and Scaling Features Chevron down icon Chevron up icon
Fixing Messy Data When Aggregating Chevron down icon Chevron up icon
Addressing Data Issues When Combining DataFrames Chevron down icon Chevron up icon
Tidying and Reshaping Data Chevron down icon Chevron up icon
Automate Data Cleaning with User-Defined Functions, Classes, and Pipelines 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.9
(24 Ratings)
5 star 91.7%
4 star 8.3%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Absar Jan 30, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
good content..waiting for the rest of the chapters
Subscriber review Packt
Bryan Edwards Jul 29, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book - the author does a great job explaining the various concepts, and the examples are very helpful
Feefo Verified review Feefo
N/A Jul 27, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Airton Leal Jun 10, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a goldmine of practical techniques for wrangling your data into shape using powerful Python libraries like pandas, NumPy, Matplotlib, scikit-learn, and the exciting newcomer - OpenAI tools.The content and inclusion of OpenAI tools, reflecting the latest advancements in the field. The hands-on approach ensures that readers not only understand the theoretical aspects of data cleaning but also acquire practical skills by working through real datasets. The clear, concise explanations and step-by-step instructions make it easy to follow along, while the numerous code snippets and illustrations help solidify understanding. Whether you're a data analyst, scientist, or engineer, this cookbook is an invaluable tool for enhancing your data cleaning capabilities and ensuring your analyses are built on a solid foundation of well-prepared data.
Amazon Verified review Amazon
James W Jun 01, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Discover how to describe your data in detail, identify data issues, and find out how to solve them using commonly used techniques and tips and tricks.Key Features I picked out from the bookVarious data cleaning techniques to reveal key insights to manipulate data of different complexities to shape them into the right form.Clean, monitor, and validate large data volumes to diagnose problems before moving on to data analysis.Book DescriptionGetting clean data to reveal insights is essential, as directly jumping into data analysis without proper data cleaning may lead to incorrect results.This book shows you tools and techniques that you can apply to clean and handle data with Python.You'll begin by getting familiar with the shape of data by using practices that can be deployed routinely with most data sources. Then, the book teaches you how to manipulate data to get it into a useful form.You'll also learn how to filter and summarise data to gain insights and better understand what makes sense and what does not, along with discovering how to operate on data to address the issues you've identified.Moving on, you'll perform key tasks, such as handling missing values, validating errors, removing duplicate data, monitoring high volumes of data, and handling outliers and invalid dates.Next, you'll cover recipes on using supervised learning and Naive Bayes analysis to identify unexpected values and classification errors, and generate visualisations for exploratory data analysis (EDA) to visualise unexpected values.Finally, you'll build functions and classes that you can reuse without modification when you have new data.By the end of this Python book, you'll be equipped with all the key skills that you need to clean data and diagnose problems within it.
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.