Examples
DataFrame.reindex supports two calling conventions

In [1]:
import numpy as np
import pandas as pd
In [2]:
index = ['Firefox', 'Chrome', 'Safari', 'IE10']
df = pd.DataFrame({
     'http_status': [200,200,404,404],
     'response_time': [0.04, 0.02, 0.07, 0.08]},
      index=index)
df
Out[2]:
http_status response_time
Firefox 200 0.04
Chrome 200 0.02
Safari 404 0.07
IE10 404 0.08

A new index and reindex the dataframe:

In [3]:
new_index= ['Safari', 'Iceweasel', 'Comodo Dragon','Chrome']
df.reindex(new_index)
Out[3]:
http_status response_time
Safari 404.0 0.07
Iceweasel NaN NaN
Comodo Dragon NaN NaN
Chrome 200.0 0.02

You can fill in the missing values by passing a value to the keyword fill_value.
Because the index is not monotonically increasing or decreasing, we cannot use
arguments to the keyword method to fill the NaN values.

In [4]:
df.reindex(new_index, fill_value=0)
Out[4]:
http_status response_time
Safari 404 0.07
Iceweasel 0 0.00
Comodo Dragon 0 0.00
Chrome 200 0.02
In [5]:
df.reindex(new_index, fill_value='missing')
Out[5]:
http_status response_time
Safari 404 0.07
Iceweasel missing missing
Comodo Dragon missing missing
Chrome 200 0.02

We can also reindex the columns.

In [6]:
df.reindex(columns=['http_status', 'user_agent'])
Out[6]:
http_status user_agent
Firefox 200 NaN
Chrome 200 NaN
Safari 404 NaN
IE10 404 NaN

Or we can use “axis-style” keyword arguments

In [7]:
df.reindex(['http_status', 'user_agent'], axis="columns")
Out[7]:
http_status user_agent
Firefox 200 NaN
Chrome 200 NaN
Safari 404 NaN
IE10 404 NaN

To further illustrate the filling functionality in reindex, we will create a dataframe
with a monotonically increasing index (for example, a sequence of dates).

In [8]:
date_index = pd.date_range('1/1/2019', periods=6, freq='D')
df2 = pd.DataFrame({"prices": [200, 201, np.nan, 200, 190, 188]},
                   index=date_index)
df2
Out[8]:
prices
2019-01-01 200.0
2019-01-02 201.0
2019-01-03 NaN
2019-01-04 200.0
2019-01-05 190.0
2019-01-06 188.0

Suppose we decide to expand the dataframe to cover a wider date range.

In [9]:
date_index2 = pd.date_range('12/29/2018', periods=10, freq='D')
df2.reindex(date_index2)
Out[9]:
prices
2018-12-29 NaN
2018-12-30 NaN
2018-12-31 NaN
2019-01-01 200.0
2019-01-02 201.0
2019-01-03 NaN
2019-01-04 200.0
2019-01-05 190.0
2019-01-06 188.0
2019-01-07 NaN

For example, to back-propagate the last valid value to fill the NaN values,
pass bfill as an argument to the method keyword.

In [10]:
df2.reindex(date_index2, method='bfill')
Out[10]:
prices
2018-12-29 200.0
2018-12-30 200.0
2018-12-31 200.0
2019-01-01 200.0
2019-01-02 201.0
2019-01-03 NaN
2019-01-04 200.0
2019-01-05 190.0
2019-01-06 188.0
2019-01-07 NaN