Search code examples
pythonpandasdataframejoin

How to expand a DataFrame by adding index values?


I have a data frame

import pandas as pd
df = pd.DataFrame({"a":[1,2,3]},index=[5,7,6])
    a
5   1
7   2
6   3

and I want to add some "missing" index values:

pd.DataFrame(index=range(3,9)).join(df)
    a
3   NaN
4   NaN
5   1.0
6   3.0
7   2.0
8   NaN

Is DataFrame.join really the way to go?

PS. For some reason I thought that df.index=range(3,9) should work, but it does not...


Solution

  • You should use reindex:

    out = df.reindex(range(3,9))
    

    Output:

         a
    3  NaN
    4  NaN
    5  1.0
    6  3.0
    7  2.0
    8  NaN
    

    Your call to join is actually reindexing internally as join is a left-join by default