Home > Net >  Horizontally concatenating dataframes gives unexpected numbers of rows
Horizontally concatenating dataframes gives unexpected numbers of rows

Time:06-21

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?

CodePudding user response:

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.

  • Related