Skip to content

Commit 23565a6

Browse files
authored
Merge pull request microsoft#164 from IndraP24/DataPrep-Update
Data Preparation README and Notebook update
2 parents 41086f1 + 1ac3f9c commit 23565a6

File tree

2 files changed

+1399
-107
lines changed

2 files changed

+1399
-107
lines changed

2-Working-With-Data/08-data-preparation/README.md

Lines changed: 285 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,294 @@ Depending on its source, raw data may contain some inconsistencies that will cau
2828

2929
- **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 for 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.
3030

31+
## Exploring DataFrame information
32+
> **Learning goal:** By the end of this subsection, you should be comfortable finding general information about the data stored in pandas DataFrames.
33+
34+
Once you have loaded your data into pandas, it will more likely than not be in a DataFrame(refer to the previous [lesson](https://github.com/microsoft/Data-Science-For-Beginners/tree/main/2-Working-With-Data/07-python#dataframe) for detailed overview). 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.
35+
36+
In order to explore this functionality, we will import the Python scikit-learn library and use an iconic dataset: the **Iris data set**.
37+
38+
```python
39+
import pandas as pd
40+
from sklearn.datasets import load_iris
41+
42+
iris = load_iris()
43+
iris_df = pd.DataFrame(data=iris['data'], columns=iris['feature_names'])
44+
```
45+
| |sepal length (cm)|sepal width (cm)|petal length (cm)|petal width (cm)|
46+
|----------------------------------------|-----------------|----------------|-----------------|----------------|
47+
|0 |5.1 |3.5 |1.4 |0.2 |
48+
|1 |4.9 |3.0 |1.4 |0.2 |
49+
|2 |4.7 |3.2 |1.3 |0.2 |
50+
|3 |4.6 |3.1 |1.5 |0.2 |
51+
|4 |5.0 |3.6 |1.4 |0.2 |
52+
53+
- **DataFrame.info**: To start off, 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:
54+
```python
55+
iris_df.info()
56+
```
57+
```
58+
RangeIndex: 150 entries, 0 to 149
59+
Data columns (total 4 columns):
60+
# Column Non-Null Count Dtype
61+
--- ------ -------------- -----
62+
0 sepal length (cm) 150 non-null float64
63+
1 sepal width (cm) 150 non-null float64
64+
2 petal length (cm) 150 non-null float64
65+
3 petal width (cm) 150 non-null float64
66+
dtypes: float64(4)
67+
memory usage: 4.8 KB
68+
```
69+
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.
70+
71+
- **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:
72+
```python
73+
iris_df.head()
74+
```
75+
```
76+
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
77+
0 5.1 3.5 1.4 0.2
78+
1 4.9 3.0 1.4 0.2
79+
2 4.7 3.2 1.3 0.2
80+
3 4.6 3.1 1.5 0.2
81+
4 5.0 3.6 1.4 0.2
82+
```
83+
- **DataFrame.tail()**: Conversely, to check the last few rows of the `DataFrame`, we use the `tail()` method:
84+
```python
85+
iris_df.tail()
86+
```
87+
```
88+
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
89+
145 6.7 3.0 5.2 2.3
90+
146 6.3 2.5 5.0 1.9
91+
147 6.5 3.0 5.2 2.0
92+
148 6.2 3.4 5.4 2.3
93+
149 5.9 3.0 5.1 1.8
94+
```
95+
> **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.
96+
97+
## Dealing with Missing Data
98+
> **Learning goal:** By the end of this subsection, you should know how to replace or remove null values from DataFrames.
99+
100+
Most of the time the datasets you want to use (of 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.
101+
102+
Pandas handles missing values in two ways. The first you've seen before in previous sections: `NaN`, or Not a Number. This is a actually a special value that is part of the IEEE floating-point specification and it is only used to indicate missing floating-point values.
103+
104+
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 regards to how they can be used.
105+
106+
Check out more about `NaN` and `None` from the [notebook](https://github.com/microsoft/Data-Science-For-Beginners/blob/main/4-Data-Science-Lifecycle/15-analyzing/notebook.ipynb)!
107+
108+
- **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:
109+
```python
110+
import numpy as np
111+
112+
example1 = pd.Series([0, np.nan, '', None])
113+
example1.isnull()
114+
```
115+
```
116+
0 False
117+
1 True
118+
2 False
119+
3 True
120+
dtype: bool
121+
```
122+
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.
123+
124+
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.
125+
126+
> **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.
127+
128+
- **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`:
129+
```python
130+
example1 = example1.dropna()
131+
example1
132+
```
133+
```
134+
0 0
135+
2
136+
dtype: object
137+
```
138+
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`.
139+
140+
Because `DataFrame`s have two dimensions, they afford more options for dropping data.
141+
142+
```python
143+
example2 = pd.DataFrame([[1, np.nan, 7],
144+
[2, 5, 8],
145+
[np.nan, 6, 9]])
146+
example2
147+
```
148+
| | 0 | 1 | 2 |
149+
|------|---|---|---|
150+
|0 |1.0|NaN|7 |
151+
|1 |2.0|5.0|8 |
152+
|2 |NaN|6.0|9 |
153+
154+
(Did you notice that pandas upcast two of the columns to floats to accommodate the `NaN`s?)
155+
156+
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:
157+
158+
```python
159+
example2.dropna()
160+
```
161+
```
162+
0 1 2
163+
1 2.0 5.0 8
164+
```
165+
If necessary, you can drop NA values from columns. Use `axis=1` to do so:
166+
```python
167+
example2.dropna(axis='columns')
168+
```
169+
```
170+
2
171+
0 7
172+
1 8
173+
2 9
174+
```
175+
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.
176+
177+
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.
178+
179+
```python
180+
example2[3] = np.nan
181+
example2
182+
```
183+
| |0 |1 |2 |3 |
184+
|------|---|---|---|---|
185+
|0 |1.0|NaN|7 |NaN|
186+
|1 |2.0|5.0|8 |NaN|
187+
|2 |NaN|6.0|9 |NaN|
188+
189+
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:
190+
```python
191+
example2.dropna(axis='rows', thresh=3)
192+
```
193+
```
194+
0 1 2 3
195+
1 2.0 5.0 8 NaN
196+
```
197+
Here, the first and last row have been dropped, because they contain only two non-null values.
198+
199+
- **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.
200+
```python
201+
example3 = pd.Series([1, np.nan, 2, None, 3], index=list('abcde'))
202+
example3
203+
```
204+
```
205+
a 1.0
206+
b NaN
207+
c 2.0
208+
d NaN
209+
e 3.0
210+
dtype: float64
211+
```
212+
You can fill all of the null entries with a single value, such as `0`:
213+
```python
214+
example3.fillna(0)
215+
```
216+
```
217+
a 1.0
218+
b 0.0
219+
c 2.0
220+
d 0.0
221+
e 3.0
222+
dtype: float64
223+
```
224+
You can **forward-fill** null values, which is to use the last valid value to fill a null:
225+
```python
226+
example3.fillna(method='ffill')
227+
```
228+
```
229+
a 1.0
230+
b 1.0
231+
c 2.0
232+
d 2.0
233+
e 3.0
234+
dtype: float64
235+
```
236+
You can also **back-fill** to propagate the next valid value backward to fill a null:
237+
```python
238+
example3.fillna(method='bfill')
239+
```
240+
```
241+
a 1.0
242+
b 2.0
243+
c 2.0
244+
d 3.0
245+
e 3.0
246+
dtype: float64
247+
```
248+
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:
249+
```python
250+
example2.fillna(method='ffill', axis=1)
251+
```
252+
```
253+
0 1 2 3
254+
0 1.0 1.0 7.0 7.0
255+
1 2.0 5.0 8.0 8.0
256+
2 NaN 6.0 9.0 9.0
257+
```
258+
Notice that when a previous value is not available for forward-filling, the null value remains.
259+
260+
> **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.
261+
262+
## Removing duplicate data
263+
264+
> **Learning goal:** By the end of this subsection, you should be comfortable identifying and removing duplicate values from DataFrames.
265+
266+
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.
267+
268+
- **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 ealier one. Let's create another example `DataFrame` to see this in action.
269+
```python
270+
example4 = pd.DataFrame({'letters': ['A','B'] * 2 + ['B'],
271+
'numbers': [1, 2, 1, 3, 3]})
272+
example4
273+
```
274+
| |letters|numbers|
275+
|------|-------|-------|
276+
|0 |A |1 |
277+
|1 |B |2 |
278+
|2 |A |1 |
279+
|3 |B |3 |
280+
|4 |B |3 |
281+
282+
```python
283+
example4.duplicated()
284+
```
285+
```
286+
0 False
287+
1 False
288+
2 True
289+
3 False
290+
4 True
291+
dtype: bool
292+
```
293+
- **Dropping duplicates: `drop_duplicates`: `drop_duplicates` simply returns a copy of the data for which all of the `duplicated` values are `False`:
294+
```python
295+
example4.drop_duplicates()
296+
```
297+
```
298+
letters numbers
299+
0 A 1
300+
1 B 2
301+
3 B 3
302+
```
303+
Both `duplicated` and `drop_duplicates` default to consider all columnsm but you can specify that they examine only a subset of columns in your `DataFrame`:
304+
```python
305+
example6.drop_duplicates(['letters'])
306+
```
307+
```
308+
letters numbers
309+
0 A 1
310+
1 B 2
311+
```
312+
313+
> **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!
314+
31315

32316
## 🚀 Challenge
33317

34-
Give the exercises in the [notebook](https://github.com/microsoft/Data-Science-For-Beginners/blob/main/4-Data-Science-Lifecycle/15-analyzing/notebook.ipynb) a try!
318+
All of the discussed materials are provided as a [Jupyter Notebook](https://github.com/microsoft/Data-Science-For-Beginners/blob/main/4-Data-Science-Lifecycle/15-analyzing/notebook.ipynb). Additionally, there are exercises present after each section, give them a try!
35319

36320
## [Post-Lecture Quiz](https://red-water-0103e7a0f.azurestaticapps.net/quiz/15)
37321

0 commit comments

Comments
 (0)