Search code examples
pythonjoinindexingmerge

Two tables to join but keep index order


I have two tables that have the same column names. I want to merge them but need to keep the order of the index:

    df1 
    x       y
0   one     1
1   two     2
2   three   3
3   four    4
4   five    5


    df2 
    x       y
0   six     6
1   seven   7
2   eight   8
3   nine    9
4   ten     10

the order of the merge is very important as I need index 0 of df1 to be first and index 0 of df2 to be second and so on.The result I want is the following:

This is to create an excel file to integrate into SAP so the order is very important . Could you help me find the correct merge for this?

    df  
    x       y
0   one     1
0   six     6
1   two     2
1   seven   7
2   three   3
2   eight   8
3   four    4
3   nine    9
4   five    5
4   ten    10
```

I tried different merges but couldn't find one that respects the order of the index.


Solution

  • You can pd.concat() the two dataframes and sort the index as next step:

    out = pd.concat([df1, df2]).sort_index(kind="stable")
    print(out)
    

    Prints:

           x   y
    0    one   1
    0    six   6
    1    two   2
    1  seven   7
    2  three   3
    2  eight   8
    3   four   4
    3   nine   9
    4   five   5
    4    ten  10