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

Arrow left icon
Profile Icon Michael Walker
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9 (24 Ratings)
Paperback May 2024 486 pages 2nd Edition
eBook
NZ$40.99 NZ$58.99
Paperback
NZ$73.99
Subscription
Free Trial
Arrow left icon
Profile Icon Michael Walker
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9 (24 Ratings)
Paperback May 2024 486 pages 2nd Edition
eBook
NZ$40.99 NZ$58.99
Paperback
NZ$73.99
Subscription
Free Trial
eBook
NZ$40.99 NZ$58.99
Paperback
NZ$73.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

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 : 9781803239873
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 : May 31, 2024
Length: 486 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803239873
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 NZ$7 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 NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 221.97
Building LLM Powered  Applications
NZ$73.99
Python Data Cleaning Cookbook
NZ$73.99
The Machine Learning Solutions Architect Handbook
NZ$73.99
Total NZ$ 221.97 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

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.