Search code examples
pythonpandassortingindexingconcatenation

Concatenating two Pandas DataFrames while maintaining index order


I am trying to concatenate two DataFrames, with the resulting DataFrame preserving the index in order of the original two. For example:

df = pd.DataFrame({'Houses':[10,20,30,40,50], 'Cities':[3,4,7,6,1]}, index = [1,2,4,6,8])


df2 = pd.DataFrame({'Houses':[15,25,35,45,55], 'Cities':[1,8,11,14,4]}, index = [0,3,5,7,9])

Using pd.concat([df, df2]) simply appends df2 to the end of df1. I am trying to instead concatenate them to produce correct index order (0 through 9).


Solution

  • Use concat with parameter sort for avoid warning and then DataFrame.sort_index:

    df = pd.concat([df, df2], sort=False).sort_index()
    
    print(df)
       Cities  Houses
    0       1      15
    1       3      10
    2       4      20
    3       8      25
    4       7      30
    5      11      35
    6       6      40
    7      14      45
    8       1      50
    9       4      55