Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading