The Pandas DataFrame/Series has several methods to handle Missing Data. When applied to a DataFrame/Series, these methods evaluate and modify the missing elements.
Preparation
Before any data manipulation can occur, two (2) new libraries will require installation.
- The Pandas library enables access to/from a DataFrame.
- The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.
To install these libraries, navigate to an IDE terminal. At the command prompt ($
), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($
). Your terminal prompt may be different.
$ pip install pandas
Hit the <Enter>
key on the keyboard to start the installation process.
$ pip install numpy
Hit the <Enter>
key on the keyboard to start the installation process.
If the installations were successful, a message displays in the terminal indicating the same.
Feel free to view the PyCharm installation guide for the required libraries.
Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.
import pandas as pd import numpy as np
DataFrame backfill() and bfill()
The DataFrame backfill()
and bfill()
methods backward fill missing data (such as np.nan
, None
, NaN
, and NaT
values) from the DataFrame/Series.
The syntax for these methods is as follows:
DataFrame.backfill(axis=None, inplace=False, limit=None, downcast=None) DataFrame.bfill(axis=None, inplace=False, limit=None, downcast=None)
axis | If zero (0) or index is selected, apply to each column. Default 0. If one (1) apply to each row. |
inplace | If set to True , the changes apply to the original DataFrame/Series. If False , the changes apply to a new DataFrame/Series. By default, False . |
limit | The maximum number of elements to backward fill. |
downcast | The only available selection is infer . This parameter attempts to convert floats (float64) to integers (int64). |
Throughout this article, we use the same DataFrame example. This DataFrame contains three (3) rows with missing data. Each example attempts to handle the missing data.
In this example, the DataFrame contains some missing data. This code will attempt to (replace) these values using the bfill()
method.
Code β Example 1
df = pd.DataFrame({'Data-1': [None, 11, 12], 'Data-2': [13, 14, None], 'Data-3': [None, 15, 16]}) print(df) result = df.bfill(axis='rows') print(result)
- Line [1] creates a dictionary of lists and saves it to
df
. - Line [2] outputs the DataFrame to the terminal. The missing values convert to
NaN
. - Line [3] backfills the
NaN
values across the rows. This output saves to theresult
variable. - Line [4] outputs the result to the terminal.
Output
df
Data-1 | Data-2 | Data-3 | |
0 | NaN | 13.0 | NaN |
1 | 11.0 | 14.0 | 15.0 |
2 | 12.0 | NaN | 16.0 |
result
Data-1 | Data-2 | Data-3 | |
0 | 11.0 | 13.0 | 15.0 |
1 | 11.0 | 14.0 | 15.0 |
2 | 12.0 | NaN | 16.0 |
π‘ Note: backfill
/bfill
tries to fill in the NaN
values with data from the same position in the next row. If there is no next row or the next row contains NaN
, the value does not change.
Code β Example 2
df = pd.DataFrame({'Data-1': [None, 11, 12], 'Data-2': [13, 14, 'NaN'], 'Data-3': [None, 15, 16]}) print(df) result = df.bfill(axis='rows') print(result)
- Line [1] creates a dictionary of lists and saves it to
df
. - Line [2] outputs the DataFrame to the terminal. The missing values convert to
NaN
. - Line [3] backfills the
NaN
values across the rows. This output saves to theresult
variable. - Line [4] outputs the result to the terminal.
Output
df
Data-1 | Data-2 | Data-3 | |
0 | NaN | 13.0 | NaN |
1 | 11.0 | 14.0 | 15.0 |
2 | 12.0 | NaN | 16.0 |
result
Data-1 | Data-2 | Data-3 | |
0 | 11.0 | 13.0 | 15.0 |
1 | 11.0 | 14.0 | 15.0 |
2 | 12.0 | NaN | 16.0 |
π‘Note: The output is identical to that in Example 1.
Code β Example 3
df = pd.DataFrame({'Data-1': [None, 11, 12], 'Data-2': [13, 14, 'NaN'], 'Data-3': [None, 15, 16]}) print(df) result = df.bfill(axis='rows', downcast='infer') print(result)
- Line [1] creates a dictionary of lists and saves it to
df
. - Line [2] outputs the DataFrame to the terminal. All missing values convert to
NaN
. - Line [3] backfills the
NaN
values across the rows. Theinfer
parameter attempts to change thedtype
across the DataFrame/Series. This output saves to theresult
variable. - Line [4] outputs the result to the terminal.
Output
df
Data-1 | Data-2 | Data-3 | |
0 | NaN | 13.0 | NaN |
1 | 11.0 | 14.0 | 15.0 |
2 | 12.0 | NaN | 16.0 |
result
Data-1 | Data-2 | Data-3 | |
0 | 11 | 13 | 15 |
1 | 11 | 14 | 15 |
2 | 12 | NaN | 16 |
DataFrame fillna()
The fillna()
method fills in the DataFrame/Series missing data (NaN
/None
) with the content of the value
parameter is shown below.
The syntax for this method is as follows:
Frame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)
value | This value is a value to fill in the missing values. This value can be a single value or a dictionary for a value-for-value replacement. Anything not in the dictionary remains unchanged. |
method | The method to use to fill in the missing values. The choices are: pad/ffill : complete with last value. backfill/bfill : complete with next value. |
axis | If zero (0) or index is selected, apply to each column. Default 0. If one (1) apply to each row. |
inplace | If set to True , the changes apply to the original DataFrame/Series. If False , the changes apply to a new DataFrame/Series. By default, False . |
limit | The maximum number of elements to backward/forward fill. |
downcast | The only available selection is the infer option. This attempts to convert floats (float64 ) to integers (int64 ). |
In this example, the DataFrame contains some missing data. This code will attempt to (replace) these values using the fillna()
method.
df = pd.DataFrame({'Data-1': [np.nan, 11, 12], 'Data-2': [13, 14, np.nan], 'Data-3': [np.nan, 15, 16]}, index=['Row-1', 'Row-2', 'Row-3']) print(df) result = df.fillna(22, downcast='infer') print(result)
- Line [1] creates a dictionary of lists and saves it to
df
. - Line [2] outputs the DataFrame to the terminal. All
np.nan
values convert toNaN
. - Line [3] fills in the missing values across the rows with the value 22. The
infer
parameter attempts to change thedtype
across the DataFrame/Series. This output saves to theresult
variable. - Line [4] outputs the result to the terminal.
Output
df
Data-1 | Data-2 | Data-3 | |
Row-1 | NaN | 13.0 | NaN |
Row-2 | 11.0 | 14.0 | 15.0 |
Row-3 | 12.0 | NaN | 16.0 |
result
Data-1 | Data-2 | Data-3 | |
Row-1 | 22 | 13 | 22 |
Row-2 | 11 | 14 | 15 |
Row-3 | 12 | 22 | 16 |
π‘ Note: The output using ffill()
is the same as if you use fillna()
and pass the method parameter as ffill
.
DataFrame dropna()
The dropna()
method removes missing data from a DataFrame/Series.
The syntax for this method is as follows:
DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
axis | If zero (0) or index is selected, apply to each column. Default 0. If one (1) apply to each row. |
how | Determines when a row/column removes from the DataFrame. The available options are: Any : if any NA values, drop row/column. All : if all NA values, then drop row/column. |
thresh | This parameter requires that there many Non-NA values. |
subset | This subset is the label(s) along the other axis to include. Must be in an array-like format and contain a list of columns in the subset. |
inplace | If set to True , the changes apply to the original DataFrame/Series. If False , the changes apply to a new DataFrame/Series. By default, False . |
Note: A list of a few possible empty values are:
'NaN'
pd.NaN
np.nan
None
NaT
In this example, the DataFrame contains some missing data. Therefore, this code will attempt to remove the rows that contain these values.
df = pd.DataFrame({'Data-1': [np.nan, 11, 12], 'Data-2': [13, 14, pd.NaT], 'Data-3': [None, 15, 16]}, index=['Row-1', 'Row-2', 'Row-3']) print(df) result = df.dropna() print(result)
- Line [1] creates a dictionary of lists and saves it to
df
. - Line [2] outputs the DataFrame to the terminal.
- Line [3] removes the rows containing missing values. This output saves to the
result
variable. - Line [4] outputs the result to the terminal.
Output
df
Data-1 | Data-2 | Data-3 | |
Row-1 | NaN | 13.0 | NaN |
Row-2 | 11.0 | 14.0 | 15.0 |
Row-3 | 12.0 | NaT | 16.0 |
result
Data-1 | Data-2 | Data-3 | |
Row-2 | 11.0 | 14.0 | 15.0 |
π‘ Note: Row-2 is the only row that contains valid data and the only row left after applying the dropna()
method.
DataFrame interpolate()
The interpolate()
method fills all NaN
values using interpolation.
The syntax for this method is as follows:
DataFrame.interpolate(method='linear', axis=0, limit=None, inplace=False, limit_direction=None, limit_area=None, downcast=None, **kwargs)
method | This parameter is the interpolation technique to use. The available options are: – linear : Ignore the index. Treat as spaced equally.– time : This parameter works on daily/high res to interpolate a specified time interval.– index , values : Use the numeric values of the index.– pad : Fill in any NaN values with existing values.– nearest/zero/slinear/quadratic/cubic/spline/barycentric/polynomial : Use the numeric values of the index. Polynomial and spline need an order (int ).– krogh/piecewise_polynomial/spline/pchip/akima/cubic/spline : Wraps around the SciPy Interpolation method(s) of similar name(s).– from_derivatives : Refers to scipy.interpolate.BPoly.from_derivatives which replaces βpiecewise_polynomial β interpolation method in Scipy 0.18. |
axis | If zero (0) or index is selected, apply to each column. Default 0. If one (1) apply to each row. |
limit | The maximum number of successive NaN values to fill. Must be more than zero (0). |
inplace | If set to True, the changes apply to the original DataFrame/Series. If False, the changes apply to a new DataFrame/Series. By default, False. |
limit_direction | The successive NaN values fill in with the specified direction. – If limit : If method pad/ffill , set direction to forward. If method backfill/bfill , set direction to backward.– If no limit: If method backfill/bfill , the default direction is backward. Otherwise forward. |
The DataFrame in this example contains missing data. This code will attempt to replace these values.
df = pd.DataFrame({'Data-1': [np.nan, 11, 12], 'Data-2': [13, 14, pd.NaT], 'Data-3': [None, 15, 16]}, index=['Row-1', 'Row-2', 'Row-3']) print(df) result = df.interpolate(method='linear', limit_direction='backward', axis=0) print(result)
- Line [1] creates a dictionary of lists and saves it to
df
. - Line [2] outputs the DataFrame to the terminal.
- Line [3] interpolates and sets the parameters to
linear
, the direction to backward, and theaxis
to zero (0). This output saves to theresult
variable. - Line [4] outputs the result to the terminal.
Output
df
Data-1 | Data-2 | Data-3 | |
Row-1 | NaN | 13.0 | NaN |
Row-2 | 11.0 | 14.0 | 15.0 |
Row-3 | 12.0 | NaT | 16.0 |
result
Data-1 | Data-2 | Data-3 | |
Row-1 | 11.0 | 13.0 | 15.0 |
Row-2 | 11.0 | 14.0 | 15.0 |
Row-3 | 12.0 | NaT | 16.0 |
Further Learning Resources
This is Part 11 of the DataFrame method series.
Also, have a look at the Pandas DataFrame methods cheat sheet!