diff --git a/open-machine-learning-jupyter-book/_toc.yml b/open-machine-learning-jupyter-book/_toc.yml index c2599a328d..dd0d11fe2a 100644 --- a/open-machine-learning-jupyter-book/_toc.yml +++ b/open-machine-learning-jupyter-book/_toc.yml @@ -29,7 +29,7 @@ parts: - file: data-science/working-with-data/pandas/introduction-and-data-structures - file: data-science/working-with-data/pandas/data-selection - file: data-science/working-with-data/pandas/advanced-pandas-techniques - - file: data-science/working-with-data/data-preparation + - file: data-science/working-with-data/data-preparation.ipynb - file: data-science/data-visualization/data-visualization sections: - file: data-science/data-visualization/visualization-distributions diff --git a/open-machine-learning-jupyter-book/data-science/working-with-data/data-preparation.ipynb b/open-machine-learning-jupyter-book/data-science/working-with-data/data-preparation.ipynb new file mode 100644 index 0000000000..5ef5816e59 --- /dev/null +++ b/open-machine-learning-jupyter-book/data-science/working-with-data/data-preparation.ipynb @@ -0,0 +1,1259 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "slideshow": { + "slide_type": "" + }, + "tags": [ + "hide-cell" + ] + }, + "outputs": [], + "source": [ + "# Install the necessary dependencies\n", + "\n", + "import os\n", + "import sys\n", + "!{sys.executable} -m pip install --quiet pandas scikit-learn numpy matplotlib jupyterlab_myst ipython" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "" + }, + "tags": [ + "remove-cell" + ] + }, + "source": [ + "---\n", + "license:\n", + " code: MIT\n", + " content: CC-BY-4.0\n", + "github: https://github.com/ocademy-ai/machine-learning\n", + "venue: By Ocademy\n", + "open_access: true\n", + "bibliography:\n", + " - https://raw.githubusercontent.com/ocademy-ai/machine-learning/main/open-machine-learning-jupyter-book/references.bib\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "# Data preparation\n", + "\n", + "Depending on its source, raw data may contain some inconsistencies that will cause challenges in analysis and modeling. In other words, this data can be categorized as “dirty” and will need to be cleaned up. This section focuses on techniques for cleaning and transforming the data to handle the challenges of missing, inaccurate, or incomplete data. Topics covered in this section will utilize Python and the Pandas library and will be [demonstrated in the notebook](../../assignments/data-science/data-preparation.ipynb) within this directory." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The importance of cleaning data\n", + "\n", + "- **Ease of use and reuse**: When data is properly organized and normalized it’s easier to search, use, and share with others.\n", + "- **Consistency**: Data science often requires working with more than one dataset, where datasets from different sources need to be joined together. Making sure that each individual data set has common standardization will ensure that the data is still useful when they are all merged into one dataset.\n", + "- **Model accuracy**: Data that has been cleaned improves the accuracy of models that rely on it." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Common cleaning goals and strategies\n", + "\n", + "- **Exploring a dataset**: Data exploration, which is covered in a [later section](../data-science-lifecycle/analyzing.md) can help you discover data that needs to be cleaned up. Visually observing values within a dataset can set expectations of what the rest of it will look like, or provide an idea of the problems that can be resolved. Exploration can involve basic querying, visualizations, and sampling.\n", + "- **Formatting**: Depending on the source, data can have inconsistencies in how it’s presented. This can cause problems in searching for and representing the value, where it’s seen within the dataset but is not properly represented in visualizations or query results. Common formatting problems involve resolving whitespace, dates, and data types. Resolving formatting issues is typically up to the people who are using the data. For example, standards on how dates and numbers are presented can differ by country.\n", + "- **Duplications**: Data that has more than one occurrence can produce inaccurate results and usually should be removed. This can be a common occurrence when joining two or more datasets together. However, there are instances where duplication in joined datasets contains pieces that can provide additional information and may need to be preserved.\n", + "- **Missing Data**: Missing data can cause inaccuracies as well as weak or biased results. Sometimes these can be resolved by a \"reload\" of the data, filling in the missing values with computation and code like Python, or simply just removing the value and corresponding data. There are numerous reasons why data may be missing and the actions that are taken to resolve these missing values can be dependent on how and why they went missing in the first place." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exploring DataFrame information\n", + "\n", + "```{note}\n", + "**Learning goal:** By the end of this subsection, you should be comfortable finding general information about the data stored in pandas DataFrames.\n", + "```\n", + "\n", + "Once you have loaded your data into Pandas, it will more likely than not be in a DataFrame. However, if the data set in your DataFrame has 60,000 rows and 400 columns, how do you even begin to get a sense of what you're working with? Fortunately, [Pandas](https://pandas.pydata.org/) provides some convenient tools to quickly look at overall information about a DataFrame in addition to the first few and last few rows.\n", + "\n", + "In order to explore this functionality, we will import the Python scikit-learn library and use an iconic dataset: the **Iris data set**.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd\n", + "from sklearn.datasets import load_iris\n", + "\n", + "iris = load_iris()\n", + "iris_df = pd.DataFrame(data=iris['data'], columns=iris['feature_names'])" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "RangeIndex: 150 entries, 0 to 149\n", + "Data columns (total 4 columns):\n", + " # Column Non-Null Count Dtype \n", + "--- ------ -------------- ----- \n", + " 0 sepal length (cm) 150 non-null float64\n", + " 1 sepal width (cm) 150 non-null float64\n", + " 2 petal length (cm) 150 non-null float64\n", + " 3 petal width (cm) 150 non-null float64\n", + "dtypes: float64(4)\n", + "memory usage: 4.8 KB\n" + ] + } + ], + "source": [ + "iris_df.info()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "From this, we know that the *Iris* dataset has 150 entries in four columns with no null entries. All of the data is stored as 64-bit floating-point numbers.\n", + "\n", + "**`DataFrame.head()`**: Next, to check the actual content of the `DataFrame`, we use the `head()` method. Let's see what the first few rows of our `iris_df` look like:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
sepal length (cm)sepal width (cm)petal length (cm)petal width (cm)
05.13.51.40.2
14.93.01.40.2
24.73.21.30.2
34.63.11.50.2
45.03.61.40.2
\n", + "
" + ], + "text/plain": [ + " sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)\n", + "0 5.1 3.5 1.4 0.2\n", + "1 4.9 3.0 1.4 0.2\n", + "2 4.7 3.2 1.3 0.2\n", + "3 4.6 3.1 1.5 0.2\n", + "4 5.0 3.6 1.4 0.2" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "iris_df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**`DataFrame.tail()`**: Conversely, to check the last few rows of the `DataFrame`, we use the `tail()` method:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
sepal length (cm)sepal width (cm)petal length (cm)petal width (cm)
1456.73.05.22.3
1466.32.55.01.9
1476.53.05.22.0
1486.23.45.42.3
1495.93.05.11.8
\n", + "
" + ], + "text/plain": [ + " sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)\n", + "145 6.7 3.0 5.2 2.3\n", + "146 6.3 2.5 5.0 1.9\n", + "147 6.5 3.0 5.2 2.0\n", + "148 6.2 3.4 5.4 2.3\n", + "149 5.9 3.0 5.1 1.8" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "iris_df.tail()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```{note}\n", + "Takeaway: Even just by looking at the metadata about the information in a DataFrame or the first and last few values in one, you can get an immediate idea about the size, shape, and content of the data you are dealing with.\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dealing with missing data\n", + "\n", + "```{note}\n", + "Learning goal: By the end of this subsection, you should know how to replace or remove null values from DataFrames.\n", + "```\n", + "\n", + "Most of the time the datasets you want to use (or have to use) have missing values in them. How missing data is handled carries with it subtle tradeoffs that can affect your final analysis and real-world outcomes?\n", + "\n", + "Pandas handles missing values in two ways. The first you've seen before in previous sections: `NaN`, or Not a Number. This is actually a special value that is part of the IEEE floating-point specification and it is only used to indicate missing floating-point values.\n", + "\n", + "For missing values apart from floats, pandas uses the Python `None` object. While it might seem confusing that you will encounter two different kinds of values that say essentially the same thing, there are sound programmatic reasons for this design choice and, in practice, going this route enables pandas to deliver a good compromise for the vast majority of cases. Notwithstanding this, both `None` and `NaN` carry restrictions that you need to be mindful of with regard to how they can be used.\n", + "\n", + "Check out more about `NaN` and `None` from the [notebook](../../assignments/data-science/analyzing-data.ipynb)!\n", + "\n", + "**Detecting null values**: In `pandas`, the `isnull()` and `notnull()` methods are your primary methods for detecting null data. Both return Boolean masks over your data. We will be using `numpy` for `NaN` values:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0 False\n", + "1 True\n", + "2 False\n", + "3 True\n", + "dtype: bool" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import numpy as np\n", + "\n", + "example1 = pd.Series([0, np.nan, '', None])\n", + "example1.isnull()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Look closely at the output. Does any of it surprise you? While `0` is an arithmetic null, it's nevertheless a perfectly good integer and pandas treats it as such. `''` is a little more subtle. While we used it in Section 1 to represent an empty string value, it is nevertheless a string object and not a representation of null as far as pandas is concerned.\n", + "\n", + "Now, let's turn this around and use these methods in a manner more like you will use them in practice. You can use Boolean masks directly as a ``Series`` or ``DataFrame`` index, which can be useful when trying to work with isolated missing (or present) values.\n", + "\n", + "Both the `isnull()` and `notnull()` methods produce similar results when you use them in `DataFrame`s: they show the results and the index of those results, which will help you enormously as you wrestle with your data.\n", + "\n", + "**Dropping null values**: Beyond identifying missing values, pandas provides a convenient means to remove null values from `Series` and `DataFrame`s. (Particularly on large data sets, it is often more advisable to simply remove missing [NA] values from your analysis than deal with them in other ways.) To see this in action, let's return to `example1`:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0 0\n", + "2 \n", + "dtype: object" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example1 = example1.dropna()\n", + "example1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that this should look like your output from `example3[example3.notnull()]`. The difference here is that, rather than just indexing on the masked values, `dropna` has removed those missing values from the `Series` `example1`.\n", + "\n", + "Because `DataFrame`s have two dimensions, they afford more options for dropping data." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
012
01.0NaN7
12.05.08
2NaN6.09
\n", + "
" + ], + "text/plain": [ + " 0 1 2\n", + "0 1.0 NaN 7\n", + "1 2.0 5.0 8\n", + "2 NaN 6.0 9" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example2 = pd.DataFrame([[1, np.nan, 7], \n", + " [2, 5, 8], \n", + " [np.nan, 6, 9]])\n", + "example2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "(Did you notice that pandas upcast two of the columns to floats to accommodate the `NaN`s?)\n", + "\n", + "You cannot drop a single value from a `DataFrame`, so you have to drop full rows or columns. Depending on what you are doing, you might want to do one or the other, and so pandas gives you options for both. Because in data science, columns generally represent variables and rows represent observations, you are more likely to drop rows of data; the default setting for `dropna()` is to drop all rows that contain any null values:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
012
12.05.08
\n", + "
" + ], + "text/plain": [ + " 0 1 2\n", + "1 2.0 5.0 8" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example2.dropna()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If necessary, you can drop NA values from columns. Use `axis=1` to do so:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
2
07
18
29
\n", + "
" + ], + "text/plain": [ + " 2\n", + "0 7\n", + "1 8\n", + "2 9" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example2.dropna(axis='columns')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice that this can drop a lot of data that you might want to keep, particularly in smaller datasets. What if you just want to drop rows or columns that contain several or even just all null values? You specify those setting in `dropna` with the `how` and `thresh` parameters.\n", + "\n", + "By default, `how='any'` (if you would like to check for yourself or see what other parameters the method has, run `example4.dropna?` in a code cell). You could alternatively specify `how='all'` so as to drop only rows or columns that contain all null values. Let's expand our example `DataFrame` to see this in action." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
0123
01.0NaN7NaN
12.05.08NaN
2NaN6.09NaN
\n", + "
" + ], + "text/plain": [ + " 0 1 2 3\n", + "0 1.0 NaN 7 NaN\n", + "1 2.0 5.0 8 NaN\n", + "2 NaN 6.0 9 NaN" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example2[3] = np.nan\n", + "example2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `thresh` parameter gives you finer-grained control: you set the number of *non-null* values that a row or column needs to have in order to be kept:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
0123
12.05.08NaN
\n", + "
" + ], + "text/plain": [ + " 0 1 2 3\n", + "1 2.0 5.0 8 NaN" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example2.dropna(axis='rows', thresh=3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here, the first and last rows have been dropped, because they contain only two non-null values.\n", + "\n", + "**Filling null values**: Depending on your dataset, it can sometimes make more sense to fill null values with valid ones rather than drop them. You could use `isnull` to do this in place, but that can be laborious, particularly if you have a lot of values to fill. Because this is such a common task in data science, pandas provides `fillna`, which returns a copy of the `Series` or `DataFrame` with the missing values replaced with one of your choosing. Let's create another example `Series` to see how this works in practice.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "a 1.0\n", + "b NaN\n", + "c 2.0\n", + "d NaN\n", + "e 3.0\n", + "dtype: float64" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example3 = pd.Series([1, np.nan, 2, None, 3], index=list('abcde'))\n", + "example3\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can fill all of the null entries with a single value, such as `0`:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "a 1.0\n", + "b 0.0\n", + "c 2.0\n", + "d 0.0\n", + "e 3.0\n", + "dtype: float64" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example3.fillna(0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As you might guess, this works the same with `DataFrame`s, but you can also specify an `axis` along which to fill null values. taking the previously used `example2` again:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
0123
01.01.07.07.0
12.05.08.08.0
2NaN6.09.09.0
\n", + "
" + ], + "text/plain": [ + " 0 1 2 3\n", + "0 1.0 1.0 7.0 7.0\n", + "1 2.0 5.0 8.0 8.0\n", + "2 NaN 6.0 9.0 9.0" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example2.fillna(method='ffill', axis=1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice that when a previous value is not available for forward-filling, the null value remains.\n", + "\n", + "\n", + "Takeaway: There are multiple ways to deal with missing values in your datasets. The specific strategy you use (removing them, replacing them, or even how you replace them) should be dictated by the particulars of that data. You will develop a better sense of how to deal with missing values the more you handle and interact with datasets." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Removing duplicate data\n", + "\n", + "\n", + "**Learning goal:** By the end of this subsection, you should be comfortable identifying and removing duplicate values from DataFrames.\n", + "\n", + "\n", + "In addition to missing data, you will often encounter duplicated data in real-world datasets. Fortunately, Pandas provides an easy means of detecting and removing duplicate entries.\n", + "\n", + "**Identifying duplicates: `duplicated`**: You can easily spot duplicate values using the `duplicated` method in Pandas, which returns a Boolean mask indicating whether an entry in a `DataFrame` is a duplicate of an earlier one. Let's create another example `DataFrame` to see this in action." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
lettersnumbers
0A1
1B2
2A1
3B3
4B3
\n", + "
" + ], + "text/plain": [ + " letters numbers\n", + "0 A 1\n", + "1 B 2\n", + "2 A 1\n", + "3 B 3\n", + "4 B 3" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example4 = pd.DataFrame({'letters': ['A','B'] * 2 + ['B'],\n", + " 'numbers': [1, 2, 1, 3, 3]})\n", + "example4" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0 False\n", + "1 False\n", + "2 True\n", + "3 False\n", + "4 True\n", + "dtype: bool" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example4.duplicated()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Dropping duplicates: `drop_duplicates`:** simply returns a copy of the data for which all of the `duplicated` values are `False`:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
lettersnumbers
0A1
1B2
3B3
\n", + "
" + ], + "text/plain": [ + " letters numbers\n", + "0 A 1\n", + "1 B 2\n", + "3 B 3" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example4.drop_duplicates()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Both `duplicated` and `drop_duplicates` default to consider all columns but you can specify that they examine only a subset of columns in your `DataFrame`:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
lettersnumbers
0A1
1B2
\n", + "
" + ], + "text/plain": [ + " letters numbers\n", + "0 A 1\n", + "1 B 2" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "example4.drop_duplicates(['letters'])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Takeaway:** Removing duplicate data is an essential part of almost every data-science project. Duplicate data can change the results of your analyses and give you inaccurate results!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Your turn! 🚀\n", + "\n", + "All of the discussed materials are provided as a [Jupyter Notebook](../../assignments/data-science/data-preparation.ipynb). Additionally, there are exercises present after each section, give them a try!\n", + "\n", + "Task - [Evaluating data from a form](../../assignments/data-science/evaluating-data-from-a-form.ipynb)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Acknowledgments\n", + "\n", + "Thanks to Microsoft for creating the open-source course [Data Science for Beginners](https://github.com/microsoft/Data-Science-For-Beginners). It inspires the majority of the content in this chapter." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/open-machine-learning-jupyter-book/data-science/working-with-data/data-preparation.md b/open-machine-learning-jupyter-book/data-science/working-with-data/data-preparation.md deleted file mode 100644 index 6e4e63f163..0000000000 --- a/open-machine-learning-jupyter-book/data-science/working-with-data/data-preparation.md +++ /dev/null @@ -1,271 +0,0 @@ ---- -jupytext: - cell_metadata_filter: -all - formats: md:myst - text_representation: - extension: .md - format_name: myst - format_version: 0.13 - jupytext_version: 1.11.5 -kernelspec: - display_name: Python 3 - language: python - name: python3 ---- - -# Data preparation - -Depending on its source, raw data may contain some inconsistencies that will cause challenges in analysis and modeling. In other words, this data can be categorized as “dirty” and will need to be cleaned up. This section focuses on techniques for cleaning and transforming the data to handle the challenges of missing, inaccurate, or incomplete data. Topics covered in this section will utilize Python and the Pandas library and will be [demonstrated in the notebook](../../assignments/data-science/data-preparation.ipynb) within this directory. - -## The importance of cleaning data - -- **Ease of use and reuse**: When data is properly organized and normalized it’s easier to search, use, and share with others. -- **Consistency**: Data science often requires working with more than one dataset, where datasets from different sources need to be joined together. Making sure that each individual data set has common standardization will ensure that the data is still useful when they are all merged into one dataset. -- **Model accuracy**: Data that has been cleaned improves the accuracy of models that rely on it. - -## Common cleaning goals and strategies - -- **Exploring a dataset**: Data exploration, which is covered in a [later section](../data-science-lifecycle/analyzing.md) can help you discover data that needs to be cleaned up. Visually observing values within a dataset can set expectations of what the rest of it will look like, or provide an idea of the problems that can be resolved. Exploration can involve basic querying, visualizations, and sampling. -- **Formatting**: Depending on the source, data can have inconsistencies in how it’s presented. This can cause problems in searching for and representing the value, where it’s seen within the dataset but is not properly represented in visualizations or query results. Common formatting problems involve resolving whitespace, dates, and data types. Resolving formatting issues is typically up to the people who are using the data. For example, standards on how dates and numbers are presented can differ by country. -- **Duplications**: Data that has more than one occurrence can produce inaccurate results and usually should be removed. This can be a common occurrence when joining two or more datasets together. However, there are instances where duplication in joined datasets contains pieces that can provide additional information and may need to be preserved. -- **Missing Data**: Missing data can cause inaccuracies as well as weak or biased results. Sometimes these can be resolved by a "reload" of the data, filling in the missing values with computation and code like Python, or simply just removing the value and corresponding data. There are numerous reasons why data may be missing and the actions that are taken to resolve these missing values can be dependent on how and why they went missing in the first place. - -## Exploring DataFrame information - -```{note} -**Learning goal:** By the end of this subsection, you should be comfortable finding general information about the data stored in pandas DataFrames. -``` - -Once you have loaded your data into Pandas, it will more likely than not be in a DataFrame. However, if the data set in your DataFrame has 60,000 rows and 400 columns, how do you even begin to get a sense of what you're working with? Fortunately, [Pandas](https://pandas.pydata.org/) provides some convenient tools to quickly look at overall information about a DataFrame in addition to the first few and last few rows. - -In order to explore this functionality, we will import the Python scikit-learn library and use an iconic dataset: the **Iris data set**. - -```{code-cell} -import pandas as pd -from sklearn.datasets import load_iris - -iris = load_iris() -iris_df = pd.DataFrame(data=iris['data'], columns=iris['feature_names']) -``` - -| |sepal length (cm)|sepal width (cm)|petal length (cm)|petal width (cm)| -|----------------------------------------|-----------------|----------------|-----------------|----------------| -|0 |5.1 |3.5 |1.4 |0.2 | -|1 |4.9 |3.0 |1.4 |0.2 | -|2 |4.7 |3.2 |1.3 |0.2 | -|3 |4.6 |3.1 |1.5 |0.2 | -|4 |5.0 |3.6 |1.4 |0.2 | - -**`DataFrame.info()`**: To start, the `info()` method is used to print a summary of the content present in a `DataFrame`. Let's take a look at this dataset to see what we have: - -```{code-cell} -iris_df.info() -``` - -From this, we know that the *Iris* dataset has 150 entries in four columns with no null entries. All of the data is stored as 64-bit floating-point numbers. - -**`DataFrame.head()`**: Next, to check the actual content of the `DataFrame`, we use the `head()` method. Let's see what the first few rows of our `iris_df` look like: - -```{code-cell} -iris_df.head() -``` - -**`DataFrame.tail()`**: Conversely, to check the last few rows of the `DataFrame`, we use the `tail()` method: - -```{code-cell} -iris_df.tail() -``` - -```{note} -**Takeaway:** Even just by looking at the metadata about the information in a DataFrame or the first and last few values in one, you can get an immediate idea about the size, shape, and content of the data you are dealing with. -``` - -## Dealing with missing data - -```{note} -**Learning goal:** By the end of this subsection, you should know how to replace or remove null values from DataFrames. -``` - -Most of the time the datasets you want to use (or have to use) have missing values in them. How missing data is handled carries with it subtle tradeoffs that can affect your final analysis and real-world outcomes? - -Pandas handles missing values in two ways. The first you've seen before in previous sections: `NaN`, or Not a Number. This is actually a special value that is part of the IEEE floating-point specification and it is only used to indicate missing floating-point values. - -For missing values apart from floats, pandas uses the Python `None` object. While it might seem confusing that you will encounter two different kinds of values that say essentially the same thing, there are sound programmatic reasons for this design choice and, in practice, going this route enables pandas to deliver a good compromise for the vast majority of cases. Notwithstanding this, both `None` and `NaN` carry restrictions that you need to be mindful of with regard to how they can be used. - -Check out more about `NaN` and `None` from the [notebook](../../assignments/data-science/analyzing-data.ipynb)! - -**Detecting null values**: In `pandas`, the `isnull()` and `notnull()` methods are your primary methods for detecting null data. Both return Boolean masks over your data. We will be using `numpy` for `NaN` values: - -```{code-cell} -import numpy as np - -example1 = pd.Series([0, np.nan, '', None]) -example1.isnull() -``` - -Look closely at the output. Does any of it surprise you? While `0` is an arithmetic null, it's nevertheless a perfectly good integer and pandas treats it as such. `''` is a little more subtle. While we used it in Section 1 to represent an empty string value, it is nevertheless a string object and not a representation of null as far as pandas is concerned. - -Now, let's turn this around and use these methods in a manner more like you will use them in practice. You can use Boolean masks directly as a ``Series`` or ``DataFrame`` index, which can be useful when trying to work with isolated missing (or present) values. - -```{note} -**Takeaway**: Both the `isnull()` and `notnull()` methods produce similar results when you use them in `DataFrame`s: they show the results and the index of those results, which will help you enormously as you wrestle with your data. -``` - -**Dropping null values**: Beyond identifying missing values, pandas provides a convenient means to remove null values from `Series` and `DataFrame`s. (Particularly on large data sets, it is often more advisable to simply remove missing [NA] values from your analysis than deal with them in other ways.) To see this in action, let's return to `example1`: - -```{code-cell} -example1 = example1.dropna() -example1 -``` - -Note that this should look like your output from `example3[example3.notnull()]`. The difference here is that, rather than just indexing on the masked values, `dropna` has removed those missing values from the `Series` `example1`. - -Because `DataFrame`s have two dimensions, they afford more options for dropping data. - -```{code-cell} -example2 = pd.DataFrame([[1, np.nan, 7], - [2, 5, 8], - [np.nan, 6, 9]]) -example2 -``` - -| | 0 | 1 | 2 | -|------|---|---|---| -|0 |1.0|NaN|7 | -|1 |2.0|5.0|8 | -|2 |NaN|6.0|9 | - -(Did you notice that pandas upcast two of the columns to floats to accommodate the `NaN`s?) - -You cannot drop a single value from a `DataFrame`, so you have to drop full rows or columns. Depending on what you are doing, you might want to do one or the other, and so pandas gives you options for both. Because in data science, columns generally represent variables and rows represent observations, you are more likely to drop rows of data; the default setting for `dropna()` is to drop all rows that contain any null values: - -```{code-cell} -example2.dropna() -``` - -If necessary, you can drop NA values from columns. Use `axis=1` to do so: - -```{code-cell} -example2.dropna(axis='columns') -``` - -Notice that this can drop a lot of data that you might want to keep, particularly in smaller datasets. What if you just want to drop rows or columns that contain several or even just all null values? You specify those setting in `dropna` with the `how` and `thresh` parameters. - -By default, `how='any'` (if you would like to check for yourself or see what other parameters the method has, run `example4.dropna?` in a code cell). You could alternatively specify `how='all'` so as to drop only rows or columns that contain all null values. Let's expand our example `DataFrame` to see this in action. - -```{code-cell} -example2[3] = np.nan -example2 -``` - -| |0 |1 |2 |3 | -|------|---|---|---|---| -|0 |1.0|NaN|7 |NaN| -|1 |2.0|5.0|8 |NaN| -|2 |NaN|6.0|9 |NaN| - -The `thresh` parameter gives you finer-grained control: you set the number of *non-null* values that a row or column needs to have in order to be kept: - -```{code-cell} -example2.dropna(axis='rows', thresh=3) -``` - -Here, the first and last rows have been dropped, because they contain only two non-null values. - -**Filling null values**: Depending on your dataset, it can sometimes make more sense to fill null values with valid ones rather than drop them. You could use `isnull` to do this in place, but that can be laborious, particularly if you have a lot of values to fill. Because this is such a common task in data science, pandas provides `fillna`, which returns a copy of the `Series` or `DataFrame` with the missing values replaced with one of your choosing. Let's create another example `Series` to see how this works in practice. - -```{code-cell} -example3 = pd.Series([1, np.nan, 2, None, 3], index=list('abcde')) -example3 -``` - -You can fill all of the null entries with a single value, such as `0`: - -```{code-cell} -example3.fillna(0) -``` - -You can **forward-fill** null values, which is to use the last valid value to fill a null: - -```{code-cell} -example3.fillna(method='ffill') -``` - -You can also **back-fill** to propagate the next valid value backward to fill a null: - -```{code-cell} -example3.fillna(method='bfill') -``` - -As you might guess, this works the same with `DataFrame`s, but you can also specify an `axis` along which to fill null values. taking the previously used `example2` again: - -```{code-cell} -example2.fillna(method='ffill', axis=1) -``` - -Notice that when a previous value is not available for forward-filling, the null value remains. - -```{note} -**Takeaway:** There are multiple ways to deal with missing values in your datasets. The specific strategy you use (removing them, replacing them, or even how you replace them) should be dictated by the particulars of that data. You will develop a better sense of how to deal with missing values the more you handle and interact with datasets. -``` - -## Removing duplicate data - -```{note} -**Learning goal:** By the end of this subsection, you should be comfortable identifying and removing duplicate values from DataFrames. -``` - -In addition to missing data, you will often encounter duplicated data in real-world datasets. Fortunately, Pandas provides an easy means of detecting and removing duplicate entries. - -**Identifying duplicates: `duplicated`**: You can easily spot duplicate values using the `duplicated` method in Pandas, which returns a Boolean mask indicating whether an entry in a `DataFrame` is a duplicate of an earlier one. Let's create another example `DataFrame` to see this in action. - -```{code-cell} -example4 = pd.DataFrame({'letters': ['A','B'] * 2 + ['B'], - 'numbers': [1, 2, 1, 3, 3]}) -example4 -``` - -| |letters|numbers| -|------|-------|-------| -|0 |A |1 | -|1 |B |2 | -|2 |A |1 | -|3 |B |3 | -|4 |B |3 | - -```{code-cell} -example4.duplicated() -``` - -**Dropping duplicates: `drop_duplicates`:** simply returns a copy of the data for which all of the `duplicated` values are `False`: - -```{code-cell} -example4.drop_duplicates() -``` - -Both `duplicated` and `drop_duplicates` default to consider all columns but you can specify that they examine only a subset of columns in your `DataFrame`: - -```{code-cell} -example4.drop_duplicates(['letters']) -``` - -```{note} -**Takeaway:** Removing duplicate data is an essential part of almost every data-science project. Duplicate data can change the results of your analyses and give you inaccurate results! -``` - -## Self study - -There are many ways to discover and approach preparing your data for analysis and modeling and cleaning the data is an important step that is a "hands on" experience. Try these challenges from Kaggle to explore techniques that this section didn't cover. - -- [Data Cleaning Challenge: Parsing Dates](https://www.kaggle.com/rtatman/data-cleaning-challenge-parsing-dates/) -- [Data Cleaning Challenge: Scale and Normalize Data](https://www.kaggle.com/rtatman/data-cleaning-challenge-scale-and-normalize-data) - -## Your turn! 🚀 - -All of the discussed materials are provided as a [Jupyter Notebook](../../assignments/data-science/data-preparation.ipynb). Additionally, there are exercises present after each section, give them a try! - -Task - [Evaluating data from a form](../../assignments/data-science/evaluating-data-from-a-form.ipynb) - -## Acknowledgments - -Thanks to Microsoft for creating the open-source course [Data Science for Beginners](https://github.com/microsoft/Data-Science-For-Beginners). It inspires the majority of the content in this chapter.