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

Horizontally concatenating dataframes gives unexpected numbers of rows

I have two data frames. One is df_1 – 217*9 size and another one is df_2 – 217*5. I want to concatenate them horizontally. Note that there is no key column. I tried to concatenate them using the following code

df = pd.concat([df_1, df_2], axis=1, ignore_index=True)

But I am getting the resulting one with 256*22 size and with unexpected results. I just need to concatenate them horizontally. What would be the issue here?

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

>Solution :

I think the problem is the index of your two data frames that are not distinct.
By giving ignore_index=True while having axis=1 it will only ignore the column-indices, not the row indices.

You could try resetting the indices while concatting like here:

pd.concat([df_1.reset_index().drop("index", axis=1), df_2.reset_index().drop("index", axis=1)], axis=1)

Edit: I’ve seen, that you accepted the answer before my last edit. My first solution still had a problem though: Leaving the ignore_index=True led to additional columns and when setting it to False, there were the index-columns multiple times included. I changed the code a bit to drop those new index columns. That might not be the best solution but I think it works.

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