Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Replace Numerical Missing Data with Values | Data Cleaning
Preprocessing Data

book
Replace Numerical Missing Data with Values

In the previous chapter, you dropped all the records containing NaN. If everything was done correct, the shape of new dataframe was (183, 12) - we lost 709 rows out of 891!

To avoid data loss because of NaNs, use different approaches to replace the missing data. The choice depends on the amount of missing data, its distribution(one or multiple columns, homogeneous or not, etc.).

The popular approaches to deal with NaNs for numerical data are:

  • replace with the mean value: good for the normal data distribution and when the number of NaNs is small.

  • replace with the mode value: good for exponential distributions and a small amount of NaNs.

  • replace with the max or min value: good if you are sure there are no outliers that may affect the result.

  • replace with some const value: for example, 0 or 1, if the possible value is either 0 or 1.

To replace the NaNs, you can use fillna():

data.fillna(some_val) # replaces NaN with some_val
# or
data.fillna(some_val, inplace=True) # change the data in-place
123
data.fillna(some_val) # replaces NaN with some_val # or data.fillna(some_val, inplace=True) # change the data in-place
copy

Also, you can use replace(old_val, new_val) to replace not only NaNs, but any other values:

data['Age'].replace(np.nan, 0) # replaces NaN with 0
# or
data['Age'].replace(np.nan, 0, inplace=True)
123
data['Age'].replace(np.nan, 0) # replaces NaN with 0 # or data['Age'].replace(np.nan, 0, inplace=True)
copy

Do you remember that titanic dataset contains missing values in the Age column? Instead of dropping rows, let's think how to replace NaNs and save data.

Task

Swipe to start coding

If share of NaNs is low enough, replace them with value - but which one? Do the following:

  1. Calculate the share of missing values in Age column. Round this value to 2 decimal places.
  2. Build the histogram of Age distribution. Use matplotlib.pyplot and method hist().

Solution

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/10db3746-c8ff-4c55-9ac3-4affa0b65c16/titanic.csv')

nans = round(ages.isna().sum() / len(ages)*100, 2) # share of NaNs
print('NaNs:', nans, '%')

# build the 'Ages' column histogram
plt.hist(ages)

Well, hope you have the similar histogram:

If yes, move on to the next chapter to deal with NaNs.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 3
single

single

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/10db3746-c8ff-4c55-9ac3-4affa0b65c16/titanic.csv')
ages = data['Age']
nans = _ _ _ # share of NaNs
print('NaNs:', nans, '%')

# build the 'Ages' column histogram
plt._ _ _

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt