Python – Data Cleansing

Python – Data Cleansing

Python – Data Cleansing

Missing data is always a problem in real life scenarios. Areas like machine learning and data mining face severe issues in the accuracy of their model predictions because of poor quality of data caused by missing values. In these areas, missing value treatment is a major point of focus to make their models more accurate and valid.

When and Why Is Data Missed?

Let us consider an online survey for a product. Many a times, people do not share all the information related to them. Few people share their experience, but not how long they are using the product; few people share how long they are using the product, their experience but not their contact information. Thus, in some or the other way a part of data is always missing, and this is very common in real time.
Let us now see how we can handle missing values (say NA or NaN) using Pandas.

# import the pandas library
import pandas as pd
import numpy as np
data_f = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])
data_f = data_f.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print data_f

Its output is as follows −

one        two      three
a   0.077988   0.476149   0.965836
b        NaN        NaN        NaN
c  -0.390208  -0.551605  -2.301950
d        NaN        NaN        NaN
e  -2.000303  -0.788201   1.510072
f  -0.930230  -0.670473   1.146615
g        NaN        NaN        NaN
h   0.085100   0.532791   0.887415

Using reindexing, we have created a DataFrame with missing values. In the output, NaN means Not a Number.

Check for Missing Values

To make detecting missing values easier (and across different array dtypes), Pandas provides the isnull() and notnull() functions, which are also methods on Series and DataFrame objects −

Example

import pandas as pd
import numpy as np
data_f = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])
data_f = data_f.reindex(['1', '2', '3', '4', '5', '6', '7', '8'])
print data_f['one'].isnull()

Its output is as follows −

1  False
2  True
3  False
4  True
5  False
6  False
7  True
8  False
Name: one, dtype: bool

Cleaning / Filling Missing Data

Pandas provides various methods for cleaning the missing values. The fillna function can “fill in” NA values with non-null data in a couple of ways, which we have illustrated in the following sections.

Replace NaN with a Scalar Value

The following program shows how you can replace "NaN" with "0".

import pandas as pd
import numpy as np
data_f = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'],columns=['one',
'two', 'three'])
data_f = data_f.reindex(['1', '2', '3'])
print data_f
print ("NaN replaced with '0':")
print data_f.fillna(0)

Its output is as follows −

one        two     three
1  -0.576991  -0.741695  0.553172
2        NaN        NaN       NaN
3   0.744328  -1.735166  1.749580
NaN replaced with '0':
one        two     three
1  -0.576991  -0.741695  0.553172
2   0.000000   0.000000  0.000000
3   0.744328  -1.735166  1.749580

Here, we are filling with value zero; instead we can also fill with any other value.

Fill NA Forward and Backward

Using the concepts of filling discussed in the ReIndexing Chapter we will fill the missing values.

Method Action
bfill/backfill Fill methods Backward
pad/fill Fill methods Forward

### Example
```
import pandas as pd
import numpy as np
data_f = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['a', 'b', 'c'])
df = data_f .reindex(['1', '2', '3', '4', '5', '6', '7', '8'])
print data_f .fillna(method='pad')
```
Its output is as follows −
```
a b c
1 0.489465 0.123165 0.489462
2 0.213597 0.998451 0.123500
3 -0.798501 -0.994651 -2.021653
4 -0.789465 -0.032165 -2.879456
5 -2.003216 -0.789851 1.032165
6 -0.879865 -0.031646 1.216540
7 -0.498412 -0.002164 1.789651
8 0.032130 0.976100 0.897410
```
## Drop Missing Values
If you want to simply exclude the missing values, then use the dropna function along with the axis argument. By default, axis=0, i.e., along row, which means that if any value within a row is NA then the whole row is excluded.
### Example
```
import pandas as pd
import numpy as np
data_f = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['a', 'b', 'c'])
df = df.reindex(['1', '2', '3', '4', '5', '6', '7', '8'])
print df.dropna()
```
Its output is as follows −
```
a b c
1 0.084153 0.032324 0.310064
2 -0.987450 -0.032165 -2.032165
3 -2.032164 -0.987104 1.546406
4 -0.054606 -0.964006 1.654065
5 0.796506 0.651060 0.894650
```
## Replace Missing (or) Generic Values
Many times, we have to replace a generic value with some specific value. We can achieve this by applying the replace method.
Replacing NA with a scalar value is equivalent behavior of the fillna() function.
### Example
```
import pandas as pd
import numpy as np
data_f = pd.DataFrame({'a':[1,2,3,4,5,20],
'b':[10,20,3,40,5,6]})
print data_f.replace({1000:10,2000:60})
```
Its output is as follows −
```
a b
0 1 10
1 2 20
2 3 3
3 4 40
4 5 5
5 6 6
```

Python – Data Operations (Prev Lesson)
(Next Lesson) Python – NoSQL Databases