Data scientists spend a large amount of their time cleaning datasets and getting them down to a form with which they can work. In fact, many data scientists argue that the initial steps of obtaining and cleaning data constitute 80 percent of the job. That’s why pandas data cleaning is one of the first skills worth building.
Whether you’re just stepping into this field or planning to step into this field, you need to be able to deal with messy data, whether that means missing values, inconsistent formatting, malformed records, or nonsensical outliers.
In this tutorial, you’ll use Python’s pandas and NumPy libraries to clean three real datasets, from a library catalog with inconsistent publication dates to a plain text file that isn’t even a table yet.
By the end of this tutorial, you’ll understand that:
- Data cleaning means dropping what you don’t need, making inconsistent values uniform, and converting columns to the right data types before you analyze anything.
DataFrame.drop()removes unwanted columns, and.set_index()turns a unique identifier column into the index so that you can look up records by label with.loc[].- The
.straccessor applies string methods and regular expressions to a whole column at once, andpd.to_numeric()converts the result to numbers. - NumPy’s
np.where()combines Boolean masks to rewrite a column based on conditions, and it nests for multiple conditions. DataFrame.map()applies a Python function to every element of a DataFrame, andread_csv()withheader=plus.rename()fixes broken header rows and column labels.
You’ll cover the following:
- Dropping unnecessary columns in a
DataFrame - Changing the index of a
DataFrame - Using
.strmethods to clean columns - Using the
DataFrame.map()method to clean the entire dataset, element-wise - Renaming columns to a more recognizable set of labels
- Skipping unnecessary rows in a CSV file
Free Bonus: Click here to get access to a free NumPy Resources Guide that points you to the best tutorials, videos, and books for improving your NumPy skills.
Here are the datasets that you’ll be using:
- BL-Flickr-Images-Book.csv – A CSV file containing information about books from the British Library
- university_towns.txt – A text file containing names of college towns in every US state
- olympics.csv – A CSV file summarizing the participation of all countries in the Summer and Winter Olympics
You can download the datasets from Real Python’s GitHub repository to follow the examples here.
Note: Using Jupyter Notebooks to follow along is a good idea, but a plain Python REPL works just as well. Whichever you choose, install the two libraries into a virtual environment first:
$ python -m pip install pandas==3.1.0 numpy==2.5.4 The examples in this tutorial were tested with Python 3.15, pandas 3.1.0, and NumPy 2.5.4. Since version 3.0, pandas stores text columns in a dedicated str data type. If you’re on an older pandas release, then you’ll see object in the output wherever this tutorial shows str, but the code works the same way.
This tutorial assumes a basic understanding of the pandas and NumPy libraries, including pandas’ workhorse Series and DataFrame objects, common methods that can be applied to these objects, and familiarity with NumPy’s NaN values.
Start by importing the required modules:
>>> import pandas as pd >>> import numpy as np With both libraries loaded, you’re ready to look at the first dataset.
Get Your Code: Click here to download the free sample code you’ll use to clean three messy real-world datasets with pandas and NumPy.
Dropping Columns in a DataFrame
Often, you’ll find that not all the categories of data in a dataset are useful to you. For example, you might have a dataset containing student information (name, grade, standard, parents’ names, and address) but want to focus on analyzing student grades.
In this case, the address or parents’ names categories are not important to you. Retaining these unneeded categories will take up unnecessary space and potentially also bog down runtime.
pandas provides a handy way of removing unwanted columns or rows from a DataFrame with the .drop() method. In this section, you’ll drop a number of columns from a DataFrame.
First, create a DataFrame out of the CSV file BL-Flickr-Images-Book.csv. In the examples below, you pass a relative path to pd.read_csv(), meaning that all of the datasets are in a folder named Datasets/ in your current working directory:
>>> df = pd.read_csv("Datasets/BL-Flickr-Images-Book.csv") >>> df.head() Identifier Edition Statement Place of Publication \ 0 206 NaN London 1 216 NaN London; Virtue & Yorston 2 218 NaN London 3 472 NaN London 4 480 A new edition, revised, etc. London Date of Publication Publisher \ 0 1879 [1878] S. Tinsley & Co. 1 1868 Virtue & Co. 2 1869 Bradbury, Evans & Co. 3 1851 James Darling 4 1857 Wertheim & Macintosh Title Author \ 0 Walter Forbes. [A novel.] By A. A A. A. 1 All for Greed. [A novel. The dedication signed... A., A. A. 2 Love the Avenger. By the author of “All for Gr... A., A. A. 3 Welsh Sketches, chiefly ecclesiastical, to the... A., E. S. 4 [The World in which I live, and my place in it... A., E. S. Contributors Corporate Author \ 0 FORBES, Walter. NaN 1 BLAZE DE BURY, Marie Pauline Rose - Baroness NaN 2 BLAZE DE BURY, Marie Pauline Rose - Baroness NaN 3 Appleyard, Ernest Silvanus. NaN 4 BROOME, John Henry. NaN Corporate Contributors Former owner Engraver Issuance type \ 0 NaN NaN NaN monographic 1 NaN NaN NaN monographic 2 NaN NaN NaN monographic 3 NaN NaN NaN monographic 4 NaN NaN NaN monographic Flickr URL \ 0 http://www.flickr.com/photos/britishlibrary/ta... 1 http://www.flickr.com/photos/britishlibrary/ta... 2 http://www.flickr.com/photos/britishlibrary/ta... 3 http://www.flickr.com/photos/britishlibrary/ta... 4 http://www.flickr.com/photos/britishlibrary/ta... Shelfmarks 0 British Library HMNTS 12641.b.30. 1 British Library HMNTS 12626.cc.2. 2 British Library HMNTS 12625.dd.1. 3 British Library HMNTS 10369.bbb.15. 4 British Library HMNTS 9007.d.28. When you look at the first five entries using the .head() method, you can see that a handful of columns provide ancillary information that would be helpful to the library but isn’t very descriptive of the books themselves: Edition Statement, Corporate Author, Corporate Contributors, Former owner, Engraver, Issuance type, and Shelfmarks. You’ll drop Contributors as well, because you won’t need it in this tutorial.
You can drop these columns in the following way:
Read the full article at https://realpython.com/python-data-cleaning-numpy-pandas/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]